An open-source, faster Devin alternative
TypeScript
Single-environment project mode: CLI link/--project, environmentless commands, dashboard and SDK (#796)
devin-ai-integration[bot]7857b367c41e
diff --git a/cli/src/api.ts b/cli/src/api.tsindex f6f31b86..db895f51 100644--- a/cli/src/api.ts+++ b/cli/src/api.ts@@ -19,13 +19,24 @@ export interface ManagedAgentSummary {updatedAt: string;}+/** Canonical environment scopes. Single-mode projects have only `default`. */+export type ProjectEnvironment = "default" | "development" | "production";++export type ProjectEnvironmentMode = "single" | "legacy";+export interface ManagedProject {id: string;slug: string;name: string;+ /**+ * `single` projects have one current deployment and no environment choice;+ * `legacy` projects keep Development and Production. Servers that predate+ * the field omit it, which means legacy.+ */+ environmentMode?: ProjectEnvironmentMode;/** One row per project agent and environment: that member's active deployment there. */environments: Array<{- name: "development" | "production";+ name: ProjectEnvironment;agentId?: string;activeDeploymentId?: string;updatedAt: string;@@ -65,7 +76,7 @@ export interface ManagedAgentEvent {export interface ManagedSecretMetadata {name: string;projectId: string;- environment: "development" | "production";+ environment: ProjectEnvironment;agentId?: string;allowedOrigins: string[];createdAt: string;@@ -85,7 +96,7 @@ export interface ManagedGitHubInstallation {export interface ManagedGitHubStatus {environments: Array<{- environment: "development" | "production";+ environment: ProjectEnvironment;state: "not_connected" | "active" | "suspended" | "deleted";installation?: ManagedGitHubInstallation;}>;@@ -130,7 +141,7 @@ export interface ModelAccessConnection {export interface ModelAccessBinding {organizationId: string;projectId: string;- environment: "development" | "production";+ environment: ProjectEnvironment;provider: "anthropic" | "openai";connectionId: string;enabled: boolean;@@ -142,7 +153,7 @@ export interface ModelAccessBinding {export interface ModelRoute {id: string;projectId: string;- environment: "development" | "production";+ environment: ProjectEnvironment;agentId?: string;connectionId: string;model: string;@@ -155,7 +166,7 @@ export interface ModelRoute {export interface AgentRuntimeVariableMetadata {name: string;projectId: string;- environment: "development" | "production";+ environment: ProjectEnvironment;agentId?: string;createdAt: string;updatedAt: string;@@ -230,7 +241,7 @@ export interface TemplateInstallation {export interface ManagedAgentWebhook {id: string;projectId: string;- environment: "development" | "production";+ environment: ProjectEnvironment;agentId: string;name: string;enabled: boolean;@@ -249,7 +260,7 @@ export interface ManagedAgentLog {timestamp: string;level: "info" | "warn" | "error";event: string;- environment: "development" | "production";+ environment: ProjectEnvironment;agentId: string;deploymentId: string;sessionId: string;@@ -304,7 +315,7 @@ export interface ManagedSessionSummary {projectId: string;agentId: string;deploymentId: string;- environment: "development" | "production" | null;+ environment: ProjectEnvironment | null;source: string;status: string;labels: Record<string, string>;@@ -343,7 +354,7 @@ export interface ManagedSessionListOptions {limit?: number;}-export type MemoryEnvironment = "development" | "production";+export type MemoryEnvironment = ProjectEnvironment;export type MemoryWriter =| { kind: "owner" }@@ -615,10 +626,18 @@ export class OpenComputerClient {return result.projects;}- createProject(name: string, slug: string) {+ createProject(+ name: string,+ slug: string,+ environmentMode?: ProjectEnvironmentMode,+ ) {return this.request<ManagedProject>("/api/managed-agents/projects", {method: "POST",- body: JSON.stringify({ name, slug }),+ body: JSON.stringify({+ name,+ slug,+ ...(environmentMode ? { environmentMode } : {}),+ }),});}@@ -636,7 +655,7 @@ export class OpenComputerClient {connectGitHub(input: {projectId: string;- environments?: Array<"development" | "production">;+ environments?: Array<ProjectEnvironment>;}) {return this.request<{ installUrl: string; authorizeUrl: string }>(`/api/managed-agents/projects/${encodeURIComponent(input.projectId)}/github/connect`,@@ -651,7 +670,7 @@ export class OpenComputerClient {attachGitHub(input: {projectId: string;- environment: "development" | "production";+ environment: ProjectEnvironment;connectionId: string;}) {return this.request<{ attached: boolean }>(@@ -668,7 +687,7 @@ export class OpenComputerClient {disconnectGitHub(input: {projectId: string;- environment: "development" | "production";+ environment: ProjectEnvironment;}) {return this.request<void>(`/api/managed-agents/projects/${encodeURIComponent(input.projectId)}/github?environment=${input.environment}`,@@ -736,7 +755,7 @@ export class OpenComputerClient {async secrets(input: {projectId: string;- environment?: "development" | "production";+ environment?: ProjectEnvironment;agentId?: string;}): Promise<ManagedSecretMetadata[]> {const query = new URLSearchParams();@@ -753,7 +772,7 @@ export class OpenComputerClient {projectId: string;name: string;value: string;- environment: "development" | "production";+ environment: ProjectEnvironment;agentId?: string;allowedOrigins: string[];}) {@@ -774,7 +793,7 @@ export class OpenComputerClient {deleteSecret(input: {projectId: string;name: string;- environment: "development" | "production";+ environment: ProjectEnvironment;agentId?: string;}) {const query = new URLSearchParams({ environment: input.environment });@@ -912,7 +931,7 @@ export class OpenComputerClient {putModelRoute(input: {projectId: string;- environment: "development" | "production";+ environment: ProjectEnvironment;connectionId: string;model: string;agentId?: string;@@ -934,7 +953,7 @@ export class OpenComputerClient {deleteModelRoute(input: {projectId: string;- environment: "development" | "production";+ environment: ProjectEnvironment;agentId?: string;}) {return this.request<void>(@@ -988,7 +1007,7 @@ export class OpenComputerClient {putModelAccessBinding(input: {projectId: string;provider: "anthropic" | "openai";- environment: "development" | "production";+ environment: ProjectEnvironment;enabled: boolean;}) {return this.request<ModelAccessBinding>(@@ -999,7 +1018,7 @@ export class OpenComputerClient {async runtimeVariables(input: {projectId: string;- environment?: "development" | "production";+ environment?: ProjectEnvironment;agentId?: string;}): Promise<AgentRuntimeVariableMetadata[]> {const query = new URLSearchParams();@@ -1018,7 +1037,7 @@ export class OpenComputerClient {projectId: string;name: string;value: string;- environment: "development" | "production";+ environment: ProjectEnvironment;agentId?: string;}) {return this.request<AgentRuntimeVariableMetadata>(@@ -1037,7 +1056,7 @@ export class OpenComputerClient {deleteRuntimeVariable(input: {projectId: string;name: string;- environment: "development" | "production";+ environment: ProjectEnvironment;agentId?: string;}) {const query = new URLSearchParams({ environment: input.environment });@@ -1050,7 +1069,7 @@ export class OpenComputerClient {async webhooks(input: {projectId: string;- environment?: "development" | "production";+ environment?: ProjectEnvironment;agentId?: string;}): Promise<ManagedAgentWebhook[]> {const query = new URLSearchParams();@@ -1066,7 +1085,7 @@ export class OpenComputerClient {createWebhook(input: {projectId: string;name: string;- environment: "development" | "production";+ environment: ProjectEnvironment;agentId: string;identity?: string;}) {@@ -1134,12 +1153,12 @@ export class OpenComputerClient {async databaseQuery(input: {projectId: string;- environment: "development" | "production";+ environment: ProjectEnvironment;sql: string;parameters?: Array<string | number | boolean | null>;}): Promise<DatabaseResult> {const response = await this.request<{- environment: "development" | "production";+ environment: ProjectEnvironment;result: DatabaseResult;}>(`/api/managed-agents/projects/${encodeURIComponent(input.projectId)}/database/query`,@@ -1297,7 +1316,7 @@ export class OpenComputerClient {logs(input: {agentId?: string;sessionId?: string;- environment?: "development" | "production";+ environment?: ProjectEnvironment;after?: string;limit?: number;}) {diff --git a/cli/src/binding.test.ts b/cli/src/binding.test.tsindex 17bd0c76..b5417151 100644--- a/cli/src/binding.test.ts+++ b/cli/src/binding.test.ts@@ -13,6 +13,7 @@ function project(): ManagedProject {id: "prj_existing",slug: "existing-project",name: "Existing project",+ environmentMode: "legacy",agents: [{ id: "agent-cloud", name: "Hello World" }],environments: [{ name: "development", updatedAt: "2026-08-09T00:00:00.000Z" },@@ -23,7 +24,7 @@ function project(): ManagedProject {};}-test("first dev can select an existing project and later reuses its binding", async () => {+test("link persists the selected project and later commands reuse its binding", async () => {const root = await mkdtemp(resolve(tmpdir(), "opencomputer-binding-"));try {const initialized = await initializeAgentProject(root);@@ -42,10 +43,11 @@ test("first dev can select an existing project and later reuses its binding", asclient,config,initialized.agentRoot,- { project: "existing-project" },+ { project: "existing-project", persist: true },);assert.equal(selected.projectId, "prj_existing");assert.equal(selected.agentId, "agent-cloud");+ assert.equal(selected.environmentMode, "legacy");assert.equal((await readManifest(initialized.agentRoot)).id, "hello-world");const projectSource = await readFile(resolve(root, "opencomputer", "project.ts"),@@ -53,9 +55,10 @@ test("first dev can select an existing project and later reuses its binding", as);assert.doesNotMatch(projectSource, /prj_existing|agent-cloud/);assert.match(projectSource, /name:/);+ const { environmentMode: _mode, ...saved } = selected;assert.deepEqual(JSON.parse(await readFile(resolve(root, ".opencomputer", "project.json"), "utf8")),- selected,+ saved,);const reused = await ensureProjectBinding(@@ -141,3 +144,80 @@ test("cloud agent ids and the resolution a command prints", async () => {);assert.match(describeResolution({ binding: null, localIds: ["worker"] }), /not linked/);});++test("--project resolves a project for one command without rewriting the saved binding", async () => {+ const root = await mkdtemp(resolve(tmpdir(), "opencomputer-binding-"));+ try {+ const initialized = await initializeAgentProject(root);+ const other: ManagedProject = {+ ...project(),+ id: "prj_other",+ slug: "other-project",+ name: "Other project",+ environmentMode: "single",+ agents: [{ id: "other-agent", name: "Other" }],+ };+ const client = {+ async projects() {+ return [project(), other];+ },+ async createProject() {+ throw new Error("unexpected create");+ },+ };+ const config = { apiUrl: "https://app.opencomputer.dev" };+ const bindingPath = resolve(root, ".opencomputer", "project.json");++ const overridden = await ensureProjectBinding(client, config, initialized.agentRoot, {+ project: "prj_other",+ });+ assert.equal(overridden.projectId, "prj_other");+ assert.equal(overridden.environmentMode, "single");+ await assert.rejects(readFile(bindingPath, "utf8"), /ENOENT/);++ const linked = await ensureProjectBinding(client, config, initialized.agentRoot, {+ project: "existing-project",+ persist: true,+ });+ assert.equal(linked.projectId, "prj_existing");+ const saved = await readFile(bindingPath, "utf8");++ const again = await ensureProjectBinding(client, config, initialized.agentRoot, {+ project: "other-project",+ });+ assert.equal(again.projectId, "prj_other");+ assert.equal(await readFile(bindingPath, "utf8"), saved);+ assert.equal(+ (await ensureProjectBinding(client, config, initialized.agentRoot)).projectId,+ "prj_existing",+ );+ assert.doesNotMatch(saved, /environmentMode|apiKey|deployment/);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("--project and --create-project cannot be combined", async () => {+ const root = await mkdtemp(resolve(tmpdir(), "opencomputer-binding-"));+ try {+ const initialized = await initializeAgentProject(root);+ await assert.rejects(+ ensureProjectBinding(+ {+ async projects() {+ return [project()];+ },+ async createProject() {+ return project();+ },+ },+ { apiUrl: "https://app.opencomputer.dev" },+ initialized.agentRoot,+ { project: "prj_existing", createProjectName: "New" },+ ),+ /cannot be combined/,+ );+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});diff --git a/cli/src/binding.ts b/cli/src/binding.tsindex af685d89..1a04852a 100644--- a/cli/src/binding.ts+++ b/cli/src/binding.ts@@ -1,7 +1,11 @@import { access, mkdir, readFile, writeFile } from "node:fs/promises";import { dirname, resolve } from "node:path";-import type { ManagedProject, OpenComputerClient } from "./api.js";+import type {+ ManagedProject,+ OpenComputerClient,+ ProjectEnvironmentMode,+} from "./api.js";import type { ResolvedConfig } from "./config.js";import {agentIdFromName,@@ -15,9 +19,28 @@ export interface ProjectBinding {agentId: string;}+/**+ * A binding plus the project's current lifecycle mode. The mode is read from+ * the project record on every resolution and never written to disk: the saved+ * binding names the project, the server says what kind of project it is.+ */+export interface ResolvedProject extends ProjectBinding {+ environmentMode: ProjectEnvironmentMode;+}+export interface ProjectBindingOptions {+ /** Use this project (id or slug) for one command; the saved binding is untouched unless `persist`. */project?: string;+ /** Create (or reuse by slug) a project and save it as this checkout's binding. */createProjectName?: string;+ /** Save the selected project as the checkout's binding (`opencomputer link`). */+ persist?: boolean;+}++export function projectEnvironmentMode(+ project: Pick<ManagedProject, "environmentMode">,+): ProjectEnvironmentMode {+ return project.environmentMode === "single" ? "single" : "legacy";}async function exists(path: string): Promise<boolean> {@@ -125,20 +148,25 @@ async function readBinding(}}-async function persistBinding(- projectRoot: string,+function bindingFor(config: ResolvedConfig,project: ManagedProject,-): Promise<ProjectBinding> {+): ProjectBinding {const agent = project.agents[0];if (!agent) throw new Error(`Project ${project.name} has no agent to bind.`);- const binding: ProjectBinding = {+ return {version: 1,apiUrl: config.apiUrl,projectId: project.id,projectName: project.name,agentId: agent.id,};+}++async function persistBinding(+ projectRoot: string,+ binding: ProjectBinding,+): Promise<ProjectBinding> {const directory = dirname(bindingPath(projectRoot));await mkdir(directory, { recursive: true, mode: 0o700 });await writeFile(@@ -149,12 +177,19 @@ async function persistBinding(return binding;}+/**+ * Resolve the project a command acts on. Precedence: an explicit `--project`+ * for this command only, then the checkout's saved binding, then a typed+ * error pointing at `opencomputer link`. Only `link` (`persist`) and project+ * creation write `.opencomputer/project.json`; an explicit `--project` on any+ * other command never rewrites what `link` chose.+ */export async function ensureProjectBinding(client: Pick<OpenComputerClient, "projects" | "createProject">,config: ResolvedConfig,agentRoot: string,options: ProjectBindingOptions = {},-): Promise<ProjectBinding> {+): Promise<ResolvedProject> {if (options.project && options.createProjectName) {throw new Error("--project and --create-project cannot be combined.");}@@ -162,16 +197,19 @@ export async function ensureProjectBinding(const projects = await client.projects();if (!options.project && !options.createProjectName) {const existing = await readBinding(projectRoot, config.apiUrl);- if (- existing &&- projects.some(- (project) =>- project.id === existing.projectId &&- project.agents.some((agent) => agent.id === existing.agentId),- )- ) {- return existing;+ const current = existing+ ? projects.find(+ (project) =>+ project.id === existing.projectId &&+ project.agents.some((agent) => agent.id === existing.agentId),+ )+ : undefined;+ if (existing && current) {+ return { ...existing, environmentMode: projectEnvironmentMode(current) };}+ throw new Error(+ "This app is not connected to a cloud project. Run `opencomputer link --project <id|slug>` or `opencomputer link --create-project <name>`.",+ );}let project = options.project@@ -183,19 +221,21 @@ export async function ensureProjectBinding(if (options.project && !project) {throw new Error(`Project ${options.project} was not found in this account.`);}- let createName = options.createProjectName;+ let persist = options.persist === true;+ const createName = options.createProjectName;if (!project && createName) {+ persist = true;const slug = agentIdFromName(createName);- project = projects.find((candidate) => candidate.slug === slug);+ project =+ projects.find((candidate) => candidate.slug === slug) ??+ (await client.createProject(createName, slug));}- if (!project && !createName) {+ if (!project) {throw new Error("This app is not connected to a cloud project. Run `opencomputer link --project <id|slug>` or `opencomputer link --create-project <name>`.",);}- project ??= await client.createProject(- createName!,- agentIdFromName(createName!),- );- return persistBinding(projectRoot, config, project);+ const binding = bindingFor(config, project);+ if (persist) await persistBinding(projectRoot, binding);+ return { ...binding, environmentMode: projectEnvironmentMode(project) };}diff --git a/cli/src/commands.test.ts b/cli/src/commands.test.tsindex 6142bbdc..f8e42fea 100644--- a/cli/src/commands.test.ts+++ b/cli/src/commands.test.ts@@ -11,6 +11,7 @@ import {shouldBindModelAccessProject,validateGitHubConnectionChoice,} from "./commands.js";+import { CLIError } from "./errors.js";test("agent event progress refreshes the inactivity deadline", () => {assert.equal(nextAgentEventDeadline(10_000, 3_000, 0, 9_000), 10_000);@@ -23,6 +24,16 @@ test("one-shot deploy defaults to development and production stays explicit", ()assert.equal(deploymentAlias("production"), "production");});+test("single-mode deploy is environmentless and refuses --alias", () => {+ assert.equal(deploymentAlias(undefined, "single"), "default");+ assert.throws(+ () => deploymentAlias("production", "single"),+ (error: unknown) =>+ error instanceof CLIError && error.code === "single_environment_project",+ );+ assert.throws(() => deploymentAlias("development", "single"), /single environment/);+});+test("model access binds the explicit or current linked project", () => {assert.equal(shouldBindModelAccessProject("test", null), true);assert.equal(@@ -47,6 +58,11 @@ test("GitHub App connections target both environments unless one is explicit", (() => githubEnvironments("staging"),/development or production/,);+ assert.deepEqual(githubEnvironments(undefined, "single"), ["default"]);+ assert.throws(+ () => githubEnvironments("production", "single"),+ /single environment/,+ );});test("GitHub App connection readiness requires every requested environment", () => {diff --git a/cli/src/commands.ts b/cli/src/commands.tsindex 186e0b33..39bb3787 100644--- a/cli/src/commands.ts+++ b/cli/src/commands.ts@@ -9,6 +9,8 @@ import {type MemoryBindings,type MemoryDocument,type MemoryDocumentMeta,+ type ProjectEnvironment,+ type ProjectEnvironmentMode,} from "./api.js";import { login, logout } from "./auth.js";import {@@ -29,7 +31,15 @@ import {describeResolution,ensureProjectBinding,findOpenComputerProjectRoot,+ projectEnvironmentMode,} from "./binding.js";+import {+ projectEnvironments,+ resolveDeployAlias,+ resolveEnvironment,+ resolveEnvironmentFilter,+ workingEnvironment,+} from "./scope.js";import {assertStarterTarget,buildAgentArtifact,@@ -88,8 +98,11 @@ export interface GlobalOptions {idempotencyKey?: string;}-export function deploymentAlias(requestedAlias?: string): string {- return requestedAlias ?? "development";+export function deploymentAlias(+ requestedAlias?: string,+ mode: ProjectEnvironmentMode = "legacy",+): string {+ return resolveDeployAlias(mode, requestedAlias);}export function shouldBindModelAccessProject(@@ -109,13 +122,15 @@ export const SERVICE_CONNECTIONS = [export function githubEnvironments(value?: string,-): Array<"development" | "production"> {- return value ? [environmentOption(value)] : ["development", "production"];+ mode: ProjectEnvironmentMode = "legacy",+): ProjectEnvironment[] {+ const filter = resolveEnvironmentFilter(mode, value);+ return filter ? [filter] : [...projectEnvironments(mode)];}export function githubEnvironmentsConnected(status: ManagedGitHubStatus,- environments: Array<"development" | "production">,+ environments: readonly ProjectEnvironment[],): boolean {return environments.every((environment) =>status.environments.some(@@ -128,7 +143,9 @@ export function selectGitHubInstallation(connections: ManagedGitHubInstallation[],selector?: string,): ManagedGitHubInstallation | undefined {- const active = connections.filter((connection) => connection.state === "active");+ const active = connections.filter(+ (connection) => connection.state === "active",+ );if (selector) {const matches = active.filter((connection) =>@@ -149,7 +166,9 @@ export function selectGitHubInstallation(throw new Error("More than one GitHub App connection is available. Pass --connection <id|account>.\n" +active- .map((connection) => ` ${connection.id} @${connection.accountLogin}`)+ .map(+ (connection) => ` ${connection.id} @${connection.accountLogin}`,+ ).join("\n"),);}@@ -202,10 +221,21 @@ function options(args: string[], name: string): string[] {function environmentOption(value: string | undefined,-): "development" | "production" {- if (!value || value === "development") return "development";- if (value === "production") return "production";- throw new Error("--environment must be development or production");+ mode: ProjectEnvironmentMode,+): ProjectEnvironment {+ return resolveEnvironment(mode, value);+}++/** An `--environment` filter with no project to say what mode applies: any canonical name. */+function legacyEnvironmentFilter(value: string): ProjectEnvironment {+ if (+ value === "default" ||+ value === "development" ||+ value === "production"+ ) {+ return value;+ }+ throw new Error("--environment must be default, development, or production");}function databaseParameter(value: string): string | number | boolean | null {@@ -362,7 +392,7 @@ async function selectedProject(client: OpenComputerClient,config: Awaited<ReturnType<typeof resolveConfig>>,reference?: string,-): Promise<{ projectId: string; agentId: string }> {+): Promise<SelectedProject> {if (reference) {const project = (await client.projects()).find((candidate) => candidate.id === reference || candidate.slug === reference,@@ -370,11 +400,26 @@ async function selectedProject(if (!project) throw new Error(`Project ${reference} was not found.`);const agent = project.agents[0];if (!agent) throw new Error(`Project ${project.name} has no agents.`);- return { projectId: project.id, agentId: agent.id };+ return {+ projectId: project.id,+ agentId: agent.id,+ environmentMode: projectEnvironmentMode(project),+ };}const root = await findOpenComputerProjectRoot(process.cwd());const binding = await ensureProjectBinding(client, config, root);- return { projectId: binding.projectId, agentId: binding.agentId };+ return {+ projectId: binding.projectId,+ agentId: binding.agentId,+ environmentMode: binding.environmentMode,+ };+}++/** A project a command acts on; `--project` selects it for this command only. */+interface SelectedProject {+ projectId: string;+ agentId: string;+ environmentMode: ProjectEnvironmentMode;}async function selectedSessionAgent(@@ -945,9 +990,7 @@ export async function runCommand(client,config,checkout.directory,- {- project: project.id,- },+ { project: project.id, persist: true },);if (globals.json) printJSON({ checkout, binding });else {@@ -982,7 +1025,7 @@ export async function runCommand(client,config,checkout.directory,- { project },+ { project, persist: true },);if (globals.json) printJSON({ checkout, binding });else {@@ -1014,8 +1057,7 @@ export async function runCommand(process.stdout.write(`\n${inspection.template.name}\n${inspection.template.description}\n` +`Source: ${inspection.repository.fullName}@${inspection.repository.commitSha.slice(0, 12)}\n` +- `Agents: ${inspection.agents.map((agent) => agent.name).join(", ")}\n` +- `Target: Development\n\n`,+ `Agents: ${inspection.agents.map((agent) => agent.name).join(", ")}\n\n`,);}if (inspection.requirements.connections.length) {@@ -1048,9 +1090,7 @@ export async function runCommand(projectName;}if (terminal && !confirmed) {- const answer = (- await terminal.question("Create this Development project? [y/N] ")- )+ const answer = (await terminal.question("Create this project? [y/N] ")).trim().toLowerCase();if (answer !== "y" && answer !== "yes") {@@ -1090,6 +1130,12 @@ export async function runCommand(projectName,idempotencyKey: crypto.randomUUID(),});+ const installedProject = (await client.projects()).find(+ (candidate) => candidate.id === installation.projectId,+ );+ const installedEnvironment = workingEnvironment(+ installedProject ? projectEnvironmentMode(installedProject) : "legacy",+ );const installationAgentId = (localAgentId?: string) =>!localAgentId || localAgentId === inspection.agents[0]?.id? installation.projectAgentId@@ -1101,7 +1147,7 @@ export async function runCommand(projectId: installation.projectId,name: requirement.name,value,- environment: "development",+ environment: installedEnvironment,agentId: installationAgentId(requirement.agentId),allowedOrigins: requirement.allowedOrigins,});@@ -1113,7 +1159,7 @@ export async function runCommand(projectId: installation.projectId,name: requirement.name,value,- environment: "development",+ environment: installedEnvironment,agentId: installationAgentId(requirement.agentId),});}@@ -1140,9 +1186,7 @@ export async function runCommand(client,config,checkout.directory,- {- project: current.projectId,- },+ { project: current.projectId, persist: true },);if (globals.json) printJSON({ installation: current, checkout, binding });else {@@ -1259,7 +1303,7 @@ export async function runCommand(`Next:\n` +enterDirectory +` npm install\n` +- ` npm run deploy -- --watch # deploy changes to Development\n` ++ ` npm run deploy -- --watch # deploy on every change\n` +(spa? ` npm run dev:web # optional local web app\n`: ""),@@ -1314,11 +1358,15 @@ export async function runCommand(const binding = await ensureProjectBinding(client, config, root, {project,createProjectName,+ persist: true,});if (globals.json) printJSON(binding);else {process.stdout.write(- `Linked this app to ${binding.projectName} (${binding.projectId}).\n`,+ `Linked this app to ${binding.projectName} (${binding.projectId})` ++ (binding.environmentMode === "single"+ ? ".\n"+ : " (legacy Development/Production project).\n"),);}return;@@ -1346,27 +1394,40 @@ export async function runCommand();}if (watch) {- if (requestedAlias && requestedAlias !== "development") {+ // Before a project can be created, only the legacy rule is knowable;+ // an existing project's mode is checked once it is resolved.+ if (+ createProjectName &&+ requestedAlias &&+ requestedAlias !== "development"+ ) {throw new Error("--watch deploys only to development; omit --alias or use --alias development",);}- await runDeploymentWatch(client, config, root, {- project,- createProjectName,- });+ await runDeploymentWatch(+ client,+ config,+ root,+ { project, createProjectName },+ { requestedAlias },+ );return;}- if (project || createProjectName) {- throw new Error("--project and --create-project require --watch");+ if (createProjectName) {+ throw new Error(+ "--create-project requires --watch or `opencomputer link`",+ );}- const alias = deploymentAlias(requestedAlias);- const binding = await ensureProjectBinding(client, config, root);+ const binding = await ensureProjectBinding(client, config, root, {+ project,+ });+ const alias = deploymentAlias(requestedAlias, binding.environmentMode);process.stderr.write(describeResolution({binding,localIds: diagnosis.resolution.agents.map((agent) => agent.localId),- alias,+ ...(binding.environmentMode === "legacy" ? { alias } : {}),}),);const results = await publishProjectDeployment(@@ -1451,8 +1512,12 @@ export async function runCommand(const action = args.shift();const projectReference = option(args, "--project");const agentOption = option(args, "--agent");- const environment = environmentOption(option(args, "--environment"));+ const environmentValue = option(args, "--environment");const project = await selectedProject(client, config, projectReference);+ const environment = environmentOption(+ environmentValue,+ project.environmentMode,+ );const agentId = agentOption? agentOption === "current"? project.agentId@@ -1592,7 +1657,10 @@ export async function runCommand(}if (action === "connect") {- const environments = githubEnvironments(option(args, "--environment"));+ const environments = githubEnvironments(+ option(args, "--environment"),+ project.environmentMode,+ );const connectionSelector = option(args, "--connection");const forceNew = flag(args, "--new");const noWait = flag(args, "--no-wait");@@ -1929,7 +1997,7 @@ export async function runCommand(? await selectedProject(client, config, projectReference): undefined;const environments = project- ? (["development", "production"] as const)+ ? projectEnvironments(project.environmentMode): [];const receipt = await client.connectModelAccess({ provider: "openai" });process.stdout.write(@@ -1966,7 +2034,11 @@ export async function runCommand();if (project) {process.stdout.write(- `Enabled Codex for ${project.projectId} (development and production).\n`,+ `Enabled Codex for ${project.projectId}${+ project.environmentMode === "legacy"+ ? " (development and production)"+ : ""+ }.\n`,);}}@@ -2040,7 +2112,7 @@ export async function runCommand(}if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);const routes = await Promise.all(- (["development", "production"] as const).map((environment) =>+ projectEnvironments(project.environmentMode).map((environment) =>client.putModelRoute({projectId: project.projectId,environment,@@ -2054,14 +2126,18 @@ export async function runCommand(if (globals.json) printJSON(routes);elseprocess.stdout.write(- `Set ${agentId ? `agent ${agentId}` : "project"} route for development and production.\n`,+ `Set ${agentId ? `agent ${agentId}` : "project"} route${+ project.environmentMode === "legacy"+ ? " for development and production"+ : ""+ }.\n`,);return;}if (action === "delete" || action === "remove") {if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);await Promise.all(- (["development", "production"] as const).map((environment) =>+ projectEnvironments(project.environmentMode).map((environment) =>client.deleteModelRoute({projectId: project.projectId,environment,@@ -2072,7 +2148,11 @@ export async function runCommand(if (globals.json) printJSON({ deleted: true });elseprocess.stdout.write(- "Removed model route from development and production.\n",+ `Removed model route${+ project.environmentMode === "legacy"+ ? " from development and production"+ : ""+ }.\n`,);return;}@@ -2083,8 +2163,12 @@ export async function runCommand(const action = args.shift();const projectReference = option(args, "--project");const agentOption = option(args, "--agent");- const environment = environmentOption(option(args, "--environment"));+ const environmentValue = option(args, "--environment");const project = await selectedProject(client, config, projectReference);+ const environment = environmentOption(+ environmentValue,+ project.environmentMode,+ );const agentId = agentOption? agentOption === "current"? project.agentId@@ -2153,8 +2237,12 @@ export async function runCommand(const action = args.shift();const projectReference = option(args, "--project");const agentOption = option(args, "--agent");- const environment = environmentOption(option(args, "--environment"));+ const environmentValue = option(args, "--environment");const project = await selectedProject(client, config, projectReference);+ const environment = environmentOption(+ environmentValue,+ project.environmentMode,+ );const agentId = await selectedSessionAgent(client,project,@@ -2290,7 +2378,7 @@ export async function runCommand(if (command === "database") {const action = args.shift();const projectReference = option(args, "--project");- const environment = environmentOption(option(args, "--environment"));+ const environmentValue = option(args, "--environment");const parameters = options(args, "--parameter").map(databaseParameter);const sql = args.shift();if (action !== "query" || !sql || args.length) {@@ -2299,6 +2387,10 @@ export async function runCommand();}const project = await selectedProject(client, config, projectReference);+ const environment = environmentOption(+ environmentValue,+ project.environmentMode,+ );const result = await client.databaseQuery({projectId: project.projectId,environment,@@ -2313,9 +2405,13 @@ export async function runCommand(if (command === "memory") {const action = args.shift();const projectReference = option(args, "--project");- const environment = environmentOption(option(args, "--environment"));+ const environmentValue = option(args, "--environment");if (!action) throw new Error(MEMORY_USAGE);const project = await selectedProject(client, config, projectReference);+ const environment = environmentOption(+ environmentValue,+ project.environmentMode,+ );const projectId = project.projectId;if (action === "export") {@@ -2548,8 +2644,8 @@ export async function runCommand(let agentId = option(args, "--agent");const sessionId = option(args, "--session");const environmentValue = option(args, "--environment");- const environment = environmentValue- ? environmentOption(environmentValue)+ let environment: ProjectEnvironment | undefined = environmentValue+ ? legacyEnvironmentFilter(environmentValue): undefined;const limitValue = option(args, "--limit");const limit = limitValue ? Number.parseInt(limitValue, 10) : 200;@@ -2557,16 +2653,31 @@ export async function runCommand(throw new Error("--limit must be between 1 and 1000");}if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);- if (!agentId && !sessionId) {- let insideProject = true;- try {- await findOpenComputerProjectRoot(process.cwd());- } catch {- insideProject = false;- }- if (insideProject) {- agentId = (await selectedProject(client, config)).agentId;+ let insideProject = true;+ try {+ await findOpenComputerProjectRoot(process.cwd());+ } catch {+ insideProject = false;+ }+ if (agentId) {+ // An explicit agent needs no local binding; its own project's mode+ // decides the environment filter. Sessions are validated by the server.+ const owner = (await client.projects()).find((candidate) =>+ candidate.agents.some((agent) => agent.id === agentId),+ );+ if (owner) {+ environment = resolveEnvironmentFilter(+ projectEnvironmentMode(owner),+ environmentValue,+ );}+ } else if (insideProject && !sessionId) {+ const project = await selectedProject(client, config);+ agentId = project.agentId;+ environment = resolveEnvironmentFilter(+ project.environmentMode,+ environmentValue,+ );}let cursor = "";let stopped = false;@@ -2602,9 +2713,13 @@ export async function runCommand(}const projectReference = option(args, "--project");const agentOption = option(args, "--agent");- const environment = environmentOption(option(args, "--environment"));+ const environmentValue = option(args, "--environment");if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);const project = await selectedProject(client, config, projectReference);+ const environment = environmentOption(+ environmentValue,+ project.environmentMode,+ );const agentId = await selectedSessionAgent(client,project,@@ -2680,13 +2795,13 @@ export async function runCommand(project,session.agent,);- const agent = developmentAgentReference(agentId);- // Sessions from the CLI run on Development, so its memory is bound.+ const agent = developmentAgentReference(agentId, project.environmentMode);+ // Sessions from the CLI run on the working environment, so its memory is bound.const documents =session.createDocuments && session.memory? await ensureMemoryDocuments(client, {projectId: project.projectId,- environment: "development",+ environment: workingEnvironment(project.environmentMode),bindings: session.memory,}): [];diff --git a/cli/src/dev.ts b/cli/src/dev.tsindex b3f0a331..f127b39f 100644--- a/cli/src/dev.ts+++ b/cli/src/dev.ts@@ -13,6 +13,7 @@ import {findOpenComputerProjectRoot,type ProjectBinding,type ProjectBindingOptions,+ type ResolvedProject,} from "./binding.js";import { startGateway } from "./local.js";import {@@ -23,6 +24,11 @@ import {type BuiltAgentArtifact,type ProjectResourceManifest,} from "./project.js";+import {+ environmentLabel,+ singleEnvironmentError,+ workingEnvironment,+} from "./scope.js";const DEVELOPMENT_ALIAS = "development";const DEBOUNCE_MS = 180;@@ -83,16 +89,17 @@ async function registerBuiltDeployment(export { cloudAgentId };+/** Publish to the project's working scope: Development for legacy projects, the single scope otherwise. */export async function publishProjectDevelopment(client: Pick<OpenComputerClient, "registerDeployment">,projectRoot: string,- binding: ProjectBinding,+ binding: ProjectBinding & Partial<Pick<ResolvedProject, "environmentMode">>,) {return publishProjectDeployment(client,projectRoot,binding,- DEVELOPMENT_ALIAS,+ workingEnvironment(binding.environmentMode ?? "legacy"),);}@@ -196,9 +203,12 @@ export function developmentWatchReadyMessage(input: {deployments: string[];watchedDirectory: string;startWebApp?: boolean;+ /** Empty for a single-mode project, which has no environment to name. */+ environmentLabel?: string;}): string {+ const label = input.environmentLabel ?? "Development";return (- `\nOpenComputer Development\n\n` ++ `\nOpenComputer${label ? ` ${label}` : ""}\n\n` +`✓ Deployment ready\n` +` Project ${input.projectName} (${input.projectId})\n` +` Agents ${input.agents.join(", ")}\n` +@@ -242,7 +252,7 @@ export async function runDeploymentWatch(config: ResolvedConfig,root: string,options: ProjectBindingOptions = {},- behavior: { startWebApp?: boolean } = {},+ behavior: { startWebApp?: boolean; requestedAlias?: string } = {},): Promise<void> {const projectRoot = await findOpenComputerProjectRoot(root);const binding = await ensureProjectBinding(@@ -251,13 +261,26 @@ export async function runDeploymentWatch(projectRoot,options,);+ if (behavior.requestedAlias !== undefined) {+ if (binding.environmentMode === "single") {+ throw singleEnvironmentError("--alias");+ }+ if (behavior.requestedAlias !== "development") {+ throw new Error(+ "--watch deploys only to development; omit --alias or use --alias development",+ );+ }+ }+ const environment = workingEnvironment(binding.environmentMode);+ const label = environmentLabel(environment);+ const agentReference = (agentId: string) => `${agentId}@${environment}`;process.stdout.write(describeResolution({binding,localIds: (await readProjectAgents(projectRoot)).map((agent) => agent.localId,),- alias: DEVELOPMENT_ALIAS,+ ...(label ? { alias: environment } : {}),}),);const gateway = await startGateway(config);@@ -271,7 +294,7 @@ export async function runDeploymentWatch(url: gateway.url,token: gateway.token,projectId: binding.projectId,- agent: `${binding.agentId}@development`,+ agent: agentReference(binding.agentId),})}\n`,{ mode: 0o600 },);@@ -293,7 +316,9 @@ export async function runDeploymentWatch(do {pending = false;try {- process.stdout.write("\nChange detected. Deploying to Development...\n");+ process.stdout.write(+ `\nChange detected. Deploying${label ? ` to ${label}` : ""}...\n`,+ );const results = await publishProjectDevelopment(client,projectRoot,@@ -311,13 +336,15 @@ export async function runDeploymentWatch(name: result.built.name,});process.stdout.write(- `${runtimeChanged ? "✓ Deployed" : "✓ Updated name for"} ${result.deployment.agentId}@development\n` ++ `${runtimeChanged ? "✓ Deployed" : "✓ Updated name for"} ${agentReference(result.deployment.agentId)}\n` +` Deployment ${result.deployment.id}\n`,);}}if (!changed) {- process.stdout.write("✓ Development is already up to date.\n");+ process.stdout.write(+ `✓ ${label || "Deployment"} is already up to date.\n`,+ );}} catch (error) {process.stderr.write(@@ -350,12 +377,13 @@ export async function runDeploymentWatch(projectName: binding.projectName,projectId: binding.projectId,dashboardUrl: projectDashboardURL(config.apiUrl, binding.projectId),- agents: initial.map(- (result) => `${result.deployment.agentId}@development`,+ agents: initial.map((result) =>+ agentReference(result.deployment.agentId),),deployments: initial.map((result) => result.deployment.id),watchedDirectory: resolve(projectRoot, "opencomputer"),startWebApp,+ environmentLabel: label,}),);if (startWebApp) web = await startReactDevServer(projectRoot);diff --git a/cli/src/memory-commands.test.ts b/cli/src/memory-commands.test.tsindex df823b78..193b63cc 100644--- a/cli/src/memory-commands.test.ts+++ b/cli/src/memory-commands.test.ts@@ -9,6 +9,7 @@ import { CLIError } from "./errors.js";import {createSessionWithMemory,ensureMemoryDocuments,+ memoryEditResumeCommand,memoryResources,saveMemoryEdit,} from "./memory-commands.js";@@ -22,25 +23,29 @@ function route(input: string | URL | Request): string {test("memory resources come from the durable inventory, undeclared ones included", async (context) => {const paths: string[] = [];- context.mock.method(globalThis, "fetch", async (input: string | URL | Request) => {- paths.push(route(input));- return Response.json({- resources: [- {- id: "scratch",- provider: { kind: "document", maxBytes: 4096 },- declared: false,- documents: 2,- },- {- id: "requirements",- provider: { kind: "document", maxBytes: 8192 },- declared: true,- documents: 3,- },- ],- });- });+ context.mock.method(+ globalThis,+ "fetch",+ async (input: string | URL | Request) => {+ paths.push(route(input));+ return Response.json({+ resources: [+ {+ id: "scratch",+ provider: { kind: "document", maxBytes: 4096 },+ declared: false,+ documents: 2,+ },+ {+ id: "requirements",+ provider: { kind: "document", maxBytes: 8192 },+ declared: true,+ documents: 3,+ },+ ],+ });+ },+ );const listing = await memoryResources(new OpenComputerClient(config),@@ -67,85 +72,95 @@ test("memory resources come from the durable inventory, undeclared ones includedtest("without the inventory route, memory resources merge every project member's active declarations", async (context) => {const paths: string[] = [];- context.mock.method(globalThis, "fetch", async (input: string | URL | Request) => {- const path = route(input);- paths.push(path);- if (path.startsWith("/api/managed-agents/projects/prj_1/memory")) {- return Response.json(- { error: { code: "not_found", message: "Route not found" } },- { status: 404 },- );- }- if (path === "/api/managed-agents/projects") {- return Response.json({- projects: [- {- id: "prj_1",- slug: "muse",- name: "Muse",- agents: [- { id: "muse", name: "Coordinator" },- { id: "muse--worker", name: "Worker" },- ],- environments: [- {- name: "development",- agentId: "muse",- activeDeploymentId: "muse:dev",- updatedAt: "2026-09-10T00:00:00.000Z",- },- {- name: "production",- agentId: "muse",- activeDeploymentId: "muse:prod",- updatedAt: "2026-09-10T00:00:00.000Z",- },- {- name: "development",- agentId: "muse--worker",- activeDeploymentId: "muse--worker:dev",- updatedAt: "2026-09-10T00:00:00.000Z",- },- {- name: "production",- agentId: "muse--worker",- updatedAt: "2026-09-10T00:00:00.000Z",- },- ],- createdAt: "2026-09-10T00:00:00.000Z",- updatedAt: "2026-09-10T00:00:00.000Z",- },- ],- });- }- if (path === "/api/managed-agents/deployments/muse%3Adev") {- return Response.json({- id: "muse:dev",- agentId: "muse",- alias: "development",- createdAt: "2026-09-10T00:00:00.000Z",- memory: [- {- id: "requirements",- provider: { kind: "document", maxBytes: 8192 },- },- ],- });- }- if (path === "/api/managed-agents/deployments/muse--worker%3Adev") {- return Response.json({- id: "muse--worker:dev",- agentId: "muse--worker",- alias: "development",- createdAt: "2026-09-10T00:00:00.000Z",- memory: [- { id: "requirements", provider: { kind: "document", maxBytes: 8192 } },- { id: "worker-notes", provider: { kind: "document", maxBytes: 4096 } },- ],- });- }- throw new Error(`unexpected request ${path}`);- });+ context.mock.method(+ globalThis,+ "fetch",+ async (input: string | URL | Request) => {+ const path = route(input);+ paths.push(path);+ if (path.startsWith("/api/managed-agents/projects/prj_1/memory")) {+ return Response.json(+ { error: { code: "not_found", message: "Route not found" } },+ { status: 404 },+ );+ }+ if (path === "/api/managed-agents/projects") {+ return Response.json({+ projects: [+ {+ id: "prj_1",+ slug: "muse",+ name: "Muse",+ agents: [+ { id: "muse", name: "Coordinator" },+ { id: "muse--worker", name: "Worker" },+ ],+ environments: [+ {+ name: "development",+ agentId: "muse",+ activeDeploymentId: "muse:dev",+ updatedAt: "2026-09-10T00:00:00.000Z",+ },+ {+ name: "production",+ agentId: "muse",+ activeDeploymentId: "muse:prod",+ updatedAt: "2026-09-10T00:00:00.000Z",+ },+ {+ name: "development",+ agentId: "muse--worker",+ activeDeploymentId: "muse--worker:dev",+ updatedAt: "2026-09-10T00:00:00.000Z",+ },+ {+ name: "production",+ agentId: "muse--worker",+ updatedAt: "2026-09-10T00:00:00.000Z",+ },+ ],+ createdAt: "2026-09-10T00:00:00.000Z",+ updatedAt: "2026-09-10T00:00:00.000Z",+ },+ ],+ });+ }+ if (path === "/api/managed-agents/deployments/muse%3Adev") {+ return Response.json({+ id: "muse:dev",+ agentId: "muse",+ alias: "development",+ createdAt: "2026-09-10T00:00:00.000Z",+ memory: [+ {+ id: "requirements",+ provider: { kind: "document", maxBytes: 8192 },+ },+ ],+ });+ }+ if (path === "/api/managed-agents/deployments/muse--worker%3Adev") {+ return Response.json({+ id: "muse--worker:dev",+ agentId: "muse--worker",+ alias: "development",+ createdAt: "2026-09-10T00:00:00.000Z",+ memory: [+ {+ id: "requirements",+ provider: { kind: "document", maxBytes: 8192 },+ },+ {+ id: "worker-notes",+ provider: { kind: "document", maxBytes: 4096 },+ },+ ],+ });+ }+ throw new Error(`unexpected request ${path}`);+ },+ );const listing = await memoryResources(new OpenComputerClient(config),@@ -166,7 +181,9 @@ test("without the inventory route, memory resources merge every project member'sdeclared: true,},]);- assert.ok(paths.includes("/api/managed-agents/deployments/muse--worker%3Adev"));+ assert.ok(+ paths.includes("/api/managed-agents/deployments/muse--worker%3Adev"),+ );assert.ok(!paths.some((path) => path.includes("muse%3Aprod")));});@@ -221,7 +238,10 @@ test("an over-limit save keeps the edited draft and says where it is", async (coassert.ok(error instanceof CLIError);assert.equal(error.code, "memory_too_large");- assert.match(error.message, /requirements\/workshop was not saved: Text is 9000 bytes/);+ assert.match(+ error.message,+ /requirements\/workshop was not saved: Text is 9000 bytes/,+ );assert.match(error.hint, new RegExp(`kept at ${draft.path}`));assert.match(error.hint, /--text-file/);assert.deepEqual(error.details, {@@ -258,7 +278,10 @@ test("a save whose response is lost keeps the draft and is reported as unconfirm/Run `opencomputer memory show requirements workshop --project prj_1 --environment development` to see whether the revision changed/,);assert.match(error.hint, new RegExp(`kept at ${draft.path}`));- assert.deepEqual(error.details, { editedTextPath: draft.path, expectedRevision: '"rev-1"' });+ assert.deepEqual(error.details, {+ editedTextPath: draft.path,+ expectedRevision: '"rev-1"',+ });await access(draft.path);} finally {await draft.cleanup();@@ -270,7 +293,12 @@ test("a save whose response is lost keeps the draft and is reported as unconfirmtest("the draft recovery command keeps project, environment, summary and shell quoting", async (context) => {context.mock.method(globalThis, "fetch", async () =>Response.json(- { error: { code: "memory_limit_exceeded", message: "Text is 9000 bytes; the limit is 8192." } },+ {+ error: {+ code: "memory_limit_exceeded",+ message: "Text is 9000 bytes; the limit is 8192.",+ },+ },{ status: 413 },),);@@ -331,26 +359,64 @@ test("a saved edit discards its draft", async (context) => {});test("--create-document creates missing bound documents, keeps existing ones, and refuses deleted ids", async (context) => {- const requests: Array<{ method: string; path: string; ifNoneMatch: string | null }> = [];- context.mock.method(globalThis, "fetch", async (input: string | URL | Request, init?: RequestInit) => {- const request = new Request(input, init);- const path = route(request);- requests.push({ method: request.method, path, ifNoneMatch: request.headers.get("if-none-match") });- const document = (id: string, revision: string) =>- Response.json({ id, title: id, text: "", summary: "", agentWrites: "enabled", revision, bytes: 0, maxBytes: 8192, updatedAt: "2026-09-10T00:00:00.000Z", writer: { kind: "owner" } }, { status: request.method === "PUT" ? 201 : 200, headers: { etag: `"${revision}"` } });- if (path.includes("/documents/fresh?")) return document("fresh", "r1");- if (path.includes("/documents/kept?")) {- return request.method === "PUT"- ? Response.json({ error: { code: "precondition_failed", message: "used" } }, { status: 412 })- : document("kept", "r9");- }- if (path.includes("/documents/gone?")) {- return request.method === "PUT"- ? Response.json({ error: { code: "precondition_failed", message: "used" } }, { status: 412 })- : Response.json({ error: { code: "not_found", message: "deleted" } }, { status: 404 });- }- throw new Error(`unexpected ${request.method} ${path}`);- });+ const requests: Array<{+ method: string;+ path: string;+ ifNoneMatch: string | null;+ }> = [];+ context.mock.method(+ globalThis,+ "fetch",+ async (input: string | URL | Request, init?: RequestInit) => {+ const request = new Request(input, init);+ const path = route(request);+ requests.push({+ method: request.method,+ path,+ ifNoneMatch: request.headers.get("if-none-match"),+ });+ const document = (id: string, revision: string) =>+ Response.json(+ {+ id,+ title: id,+ text: "",+ summary: "",+ agentWrites: "enabled",+ revision,+ bytes: 0,+ maxBytes: 8192,+ updatedAt: "2026-09-10T00:00:00.000Z",+ writer: { kind: "owner" },+ },+ {+ status: request.method === "PUT" ? 201 : 200,+ headers: { etag: `"${revision}"` },+ },+ );+ if (path.includes("/documents/fresh?")) return document("fresh", "r1");+ if (path.includes("/documents/kept?")) {+ return request.method === "PUT"+ ? Response.json(+ { error: { code: "precondition_failed", message: "used" } },+ { status: 412 },+ )+ : document("kept", "r9");+ }+ if (path.includes("/documents/gone?")) {+ return request.method === "PUT"+ ? Response.json(+ { error: { code: "precondition_failed", message: "used" } },+ { status: 412 },+ )+ : Response.json(+ { error: { code: "not_found", message: "deleted" } },+ { status: 404 },+ );+ }+ throw new Error(`unexpected ${request.method} ${path}`);+ },+ );const client = new OpenComputerClient(config);const ensured = await ensureMemoryDocuments(client, {@@ -366,11 +432,16 @@ test("--create-document creates missing bound documents, keeps existing ones, an{ resource: "topics", id: "fresh", created: true, revision: "r1" },{ resource: "profile", id: "kept", created: false, revision: "r9" },]);- assert.deepEqual(requests.map((request) => `${request.method} ${request.path.split("?")[0]} ${request.ifNoneMatch ?? ""}`.trim()), [- "PUT /api/managed-agents/projects/prj_1/memory/topics/documents/fresh *",- "PUT /api/managed-agents/projects/prj_1/memory/profile/documents/kept *",- "GET /api/managed-agents/projects/prj_1/memory/profile/documents/kept",- ]);+ assert.deepEqual(+ requests.map((request) =>+ `${request.method} ${request.path.split("?")[0]} ${request.ifNoneMatch ?? ""}`.trim(),+ ),+ [+ "PUT /api/managed-agents/projects/prj_1/memory/topics/documents/fresh *",+ "PUT /api/managed-agents/projects/prj_1/memory/profile/documents/kept *",+ "GET /api/managed-agents/projects/prj_1/memory/profile/documents/kept",+ ],+ );await assert.rejects(ensureMemoryDocuments(client, {@@ -378,7 +449,10 @@ test("--create-document creates missing bound documents, keeps existing ones, anenvironment: "development",bindings: { topics: { scope: "document", id: "gone" } },}),- (error: unknown) => error instanceof CLIError && error.code === "memory_document_deleted" && /reserved/.test(error.message),+ (error: unknown) =>+ error instanceof CLIError &&+ error.code === "memory_document_deleted" &&+ /reserved/.test(error.message),);});@@ -387,43 +461,83 @@ test("--create-document creates missing bound documents, keeps existing ones, antest("one caller key with different bindings is a conflict, not a second session", async (context) => {const receipts = new Map<string, { body: string; id: string }>();let created = 0;- context.mock.method(globalThis, "fetch", async (input: string | URL | Request, init?: RequestInit) => {- const request = new Request(input, init);- assert.equal(route(request), "/api/managed-agents/sessions");- const key = request.headers.get("idempotency-key");- assert.ok(key, "the CLI sends the header");- const body = await request.text();- const receipt = receipts.get(key);- if (receipt && receipt.body !== body) {+ context.mock.method(+ globalThis,+ "fetch",+ async (input: string | URL | Request, init?: RequestInit) => {+ const request = new Request(input, init);+ assert.equal(route(request), "/api/managed-agents/sessions");+ const key = request.headers.get("idempotency-key");+ assert.ok(key, "the CLI sends the header");+ const body = await request.text();+ const receipt = receipts.get(key);+ if (receipt && receipt.body !== body) {+ return Response.json(+ {+ error: {+ code: "idempotency_conflict",+ message:+ "Idempotency-Key was already used with different session input",+ },+ },+ { status: 409 },+ );+ }+ if (receipt) {+ return Response.json(+ { session: { id: receipt.id, status: "idle" } },+ { status: 200 },+ );+ }+ created += 1;+ const id = `ses-${String(created)}`;+ receipts.set(key, { body, id });return Response.json(- { error: { code: "idempotency_conflict", message: "Idempotency-Key was already used with different session input" } },- { status: 409 },+ { session: { id, status: "connecting" } },+ { status: 201 },);- }- if (receipt) {- return Response.json({ session: { id: receipt.id, status: "idle" } }, { status: 200 });- }- created += 1;- const id = `ses-${String(created)}`;- receipts.set(key, { body, id });- return Response.json({ session: { id, status: "connecting" } }, { status: 201 });- });+ },+ );const client = new OpenComputerClient(config, "topic/workshop/1");- const workshop = { topics: { scope: "document" as const, id: "workshop", access: "read-write" as const } };- const other = { topics: { scope: "document" as const, id: "other", access: "read-write" as const } };+ const workshop = {+ topics: {+ scope: "document" as const,+ id: "workshop",+ access: "read-write" as const,+ },+ };+ const other = {+ topics: {+ scope: "document" as const,+ id: "other",+ access: "read-write" as const,+ },+ };- const first = await createSessionWithMemory(client, "muse@development", workshop);+ const first = await createSessionWithMemory(+ client,+ "muse@development",+ workshop,+ );assert.equal(first.created, true);- const replayed = await createSessionWithMemory(client, "muse@development", workshop);+ const replayed = await createSessionWithMemory(+ client,+ "muse@development",+ workshop,+ );assert.equal(replayed.created, false);assert.equal(replayed.session.id, first.session.id);await assert.rejects(createSessionWithMemory(client, "muse@development", other),- (error: unknown) => error instanceof CLIError && error.code === "session_idempotency_conflict",+ (error: unknown) =>+ error instanceof CLIError &&+ error.code === "session_idempotency_conflict",);await assert.rejects(createSessionWithMemory(client, "muse@development"),- (error: unknown) => error instanceof CLIError && error.code === "session_idempotency_conflict",+ (error: unknown) =>+ error instanceof CLIError &&+ error.code === "session_idempotency_conflict",);assert.equal(created, 1);assert.equal(receipts.size, 1);@@ -432,25 +546,58 @@ test("one caller key with different bindings is a conflict, not a second sessiontest("session create sends bindings, reports replay, and names a reused key's conflict", async (context) => {const bodies: Array<Record<string, unknown>> = [];let status = 201;- context.mock.method(globalThis, "fetch", async (input: string | URL | Request, init?: RequestInit) => {- const request = new Request(input, init);- assert.equal(route(request), "/api/managed-agents/sessions");- bodies.push((await request.json()) as Record<string, unknown>);- if (status === 409) {- return Response.json({ error: { code: "idempotency_conflict", message: "Idempotency-Key was already used with different session input" } }, { status });- }- return Response.json({ session: { id: "ses-1", status: "connecting" }, deployment: { id: "muse:dev", agentId: "muse", alias: "development" } }, { status });- });+ context.mock.method(+ globalThis,+ "fetch",+ async (input: string | URL | Request, init?: RequestInit) => {+ const request = new Request(input, init);+ assert.equal(route(request), "/api/managed-agents/sessions");+ bodies.push((await request.json()) as Record<string, unknown>);+ if (status === 409) {+ return Response.json(+ {+ error: {+ code: "idempotency_conflict",+ message:+ "Idempotency-Key was already used with different session input",+ },+ },+ { status },+ );+ }+ return Response.json(+ {+ session: { id: "ses-1", status: "connecting" },+ deployment: { id: "muse:dev", agentId: "muse", alias: "development" },+ },+ { status },+ );+ },+ );const client = new OpenComputerClient(config, "topic/workshop/1");- const memory = { topics: { scope: "document" as const, id: "workshop", access: "read-write" as const } };+ const memory = {+ topics: {+ scope: "document" as const,+ id: "workshop",+ access: "read-write" as const,+ },+ };- const created = await createSessionWithMemory(client, "muse@development", memory);+ const created = await createSessionWithMemory(+ client,+ "muse@development",+ memory,+ );assert.equal(created.created, true);assert.equal(created.session.id, "ses-1");assert.deepEqual(bodies[0], { agentId: "muse@development", memory });status = 200;- const replayed = await createSessionWithMemory(client, "muse@development", memory);+ const replayed = await createSessionWithMemory(+ client,+ "muse@development",+ memory,+ );assert.equal(replayed.created, false);status = 201;@@ -460,6 +607,28 @@ test("session create sends bindings, reports replay, and names a reused key's costatus = 409;await assert.rejects(createSessionWithMemory(client, "muse@development", memory),- (error: unknown) => error instanceof CLIError && error.code === "session_idempotency_conflict" && /different agent, deployment, environment or memory bindings/.test(error.message),+ (error: unknown) =>+ error instanceof CLIError &&+ error.code === "session_idempotency_conflict" &&+ /different agent, deployment, environment or memory bindings/.test(+ error.message,+ ),+ );+});++test("memory edit resume commands omit --environment for the single scope", () => {+ const base = {+ projectId: "prj_1",+ resource: "notes",+ id: "todo",+ draftPath: "/tmp/draft",+ };+ assert.equal(+ memoryEditResumeCommand({ ...base, environment: "default" }),+ "opencomputer memory edit notes todo --project prj_1 --text-file /tmp/draft",+ );+ assert.equal(+ memoryEditResumeCommand({ ...base, environment: "production" }),+ "opencomputer memory edit notes todo --project prj_1 --environment production --text-file /tmp/draft",);});diff --git a/cli/src/memory-commands.ts b/cli/src/memory-commands.tsindex 07cf7e16..9f36a985 100644--- a/cli/src/memory-commands.ts+++ b/cli/src/memory-commands.ts@@ -75,13 +75,18 @@ export async function memoryResources(for (const deploymentId of deploymentIds) {const deployment = await client.deployment(deploymentId);for (const declaration of deployment.memory ?? []) {- if (typeof declaration.id !== "string" || byResource.has(declaration.id)) {+ if (+ typeof declaration.id !== "string" ||+ byResource.has(declaration.id)+ ) {continue;}byResource.set(declaration.id, {id: declaration.id,provider: {- ...(declaration.provider?.kind ? { kind: declaration.provider.kind } : {}),+ ...(declaration.provider?.kind+ ? { kind: declaration.provider.kind }+ : {}),...(typeof declaration.provider?.maxBytes === "number"? { maxBytes: declaration.provider.maxBytes }: {}),@@ -119,6 +124,11 @@ export function shellWord(value: string): string {* project's Development by default), the same summary, and a path the* shell reads back whatever it contains.*/+/** `--environment` for a legacy scope; single-mode projects refuse the flag, so `default` says nothing. */+function environmentFlag(environment: MemoryEnvironment): string[] {+ return environment === "default" ? [] : ["--environment", environment];+}+export function memoryEditResumeCommand(input: {projectId: string;resource: string;@@ -133,8 +143,7 @@ export function memoryEditResumeCommand(input: {shellWord(input.id),"--project",shellWord(input.projectId),- "--environment",- input.environment,+ ...environmentFlag(input.environment),...(input.summary !== undefined? ["--summary", shellWord(input.summary)]: []),@@ -169,9 +178,7 @@ export async function saveMemoryEdit(await draft?.discard();return document;} catch (error) {- const kept = draft- ? { editedTextPath: draft.path }- : {};+ const kept = draft ? { editedTextPath: draft.path } : {};const resume = draft? ` Your edited text is kept at ${draft.path}; save it with ` +`\`${memoryEditResumeCommand({ ...input, draftPath: draft.path })}\`.`@@ -181,15 +188,19 @@ export async function saveMemoryEdit(throw new CLIError("memory_save_unconfirmed",`${input.resource}/${input.id} may or may not have been saved: ${failure.message}`,- `Run \`opencomputer memory show ${shellWord(input.resource)} ${shellWord(input.id)} --project ${shellWord(input.projectId)} --environment ${input.environment}\` to see whether the revision changed before saving again.` ++ `Run \`opencomputer memory show ${shellWord(input.resource)} ${shellWord(input.id)} --project ${shellWord(input.projectId)}${environmentFlag(+ input.environment,+ )+ .map((word) => ` ${word}`)+ .join(+ "",+ )}\` to see whether the revision changed before saving again.` +resume,{ ...kept, expectedRevision: input.etag },);}if (error.status === 412) {- const latest = await client- .memoryDocument(input)- .catch(() => null);+ const latest = await client.memoryDocument(input).catch(() => null);throw new CLIError("memory_conflict",`${input.resource}/${input.id} changed since you opened it` +@@ -263,14 +274,24 @@ export async function ensureMemoryDocuments(title: binding.id,text: "",});- ensured.push({ resource, id: binding.id, created: true, revision: document.revision });+ ensured.push({+ resource,+ id: binding.id,+ created: true,+ revision: document.revision,+ });continue;} catch (error) {if (!(error instanceof APIError && error.status === 412)) throw error;}try {const { document } = await client.memoryDocument(target);- ensured.push({ resource, id: binding.id, created: false, revision: document.revision });+ ensured.push({+ resource,+ id: binding.id,+ created: false,+ revision: document.revision,+ });} catch (error) {if (error instanceof APIError && error.status === 404) {throw new CLIError(diff --git a/cli/src/project.test.ts b/cli/src/project.test.tsindex aae7be2e..0bd4ad6c 100644--- a/cli/src/project.test.ts+++ b/cli/src/project.test.ts@@ -230,7 +230,7 @@ export default defineSchedule({id: "weekday-hygiene",cron: "0 9 * * 1-5",timezone: "America/Los_Angeles",- enabled: ["development", "production"],+ enabled: ["default", "development", "production"],overlap: "skip",dispatch: {text: "Run feature flag hygiene.",@@ -246,7 +246,7 @@ export default defineSchedule({agentId: "hello-world",cron: "0 9 * * 1-5",timezone: "America/Los_Angeles",- enabled: ["development", "production"],+ enabled: ["default", "development", "production"],overlap: "skip",dispatch: {text: "Run feature flag hygiene.",diff --git a/cli/src/project.ts b/cli/src/project.tsindex 67b34d1a..3ec8505c 100644--- a/cli/src/project.ts+++ b/cli/src/project.ts@@ -143,7 +143,12 @@ export interface ScheduleDefinitionManifest {agentId: string;cron: string;timezone: string;- enabled: Array<"development" | "production">;+ /**+ * Environments the schedule runs in. `production` also covers a+ * single-environment project's `default` scope; `development` alone+ * leaves it manual there.+ */+ enabled: Array<"default" | "development" | "production">;overlap: "skip" | "allow";dispatch: {text?: string;@@ -568,12 +573,12 @@ function openComputerAgent() {export default defineConfig(({ command }) => {const dev = command === "serve" ? openComputerDev() : undefined;+ // A bare agent id addresses the live deployment: Production for a legacy+ // project, the single environment otherwise.return {plugins: [react()],define: {- __OPENCOMPUTER_AGENT__: JSON.stringify(- dev?.agent ?? \`\${openComputerAgent()}@production\`,- ),+ __OPENCOMPUTER_AGENT__: JSON.stringify(dev?.agent ?? openComputerAgent()),},...(dev ? { server: {proxy: {@@ -2194,7 +2199,9 @@ function scheduleDefinition(!enabled.length ||enabled.some((environment) =>- environment !== "development" && environment !== "production",+ environment !== "default" &&+ environment !== "development" &&+ environment !== "production",)) {throw new Error(`${path} enabled environments are invalid`);diff --git a/cli/src/scope.test.ts b/cli/src/scope.test.tsnew file mode 100644index 00000000..54d0ac9b--- /dev/null+++ b/cli/src/scope.test.ts@@ -0,0 +1,35 @@+import assert from "node:assert/strict";+import test from "node:test";++import { CLIError } from "./errors.js";+import {+ projectEnvironments,+ resolveEnvironment,+ resolveEnvironmentFilter,+ workingEnvironment,+} from "./scope.js";++test("legacy projects keep Development as the default and Production explicit", () => {+ assert.equal(resolveEnvironment("legacy", undefined), "development");+ assert.equal(resolveEnvironment("legacy", "production"), "production");+ assert.throws(() => resolveEnvironment("legacy", "default"), /development or production/);+ assert.equal(resolveEnvironmentFilter("legacy", undefined), undefined);+ assert.deepEqual(projectEnvironments("legacy"), ["development", "production"]);+ assert.equal(workingEnvironment("legacy"), "development");+});++test("single-mode projects resolve to the one scope and refuse an environment flag", () => {+ assert.equal(resolveEnvironment("single", undefined), "default");+ assert.equal(resolveEnvironmentFilter("single", undefined), "default");+ for (const value of ["development", "production", "default"]) {+ assert.throws(+ () => resolveEnvironment("single", value),+ (error: unknown) =>+ error instanceof CLIError &&+ error.code === "single_environment_project" &&+ /--environment/.test(error.message),+ );+ }+ assert.deepEqual(projectEnvironments("single"), ["default"]);+ assert.equal(workingEnvironment("single"), "default");+});diff --git a/cli/src/scope.ts b/cli/src/scope.tsnew file mode 100644index 00000000..8d06f87b--- /dev/null+++ b/cli/src/scope.ts@@ -0,0 +1,98 @@+import type { ProjectEnvironment, ProjectEnvironmentMode } from "./api.js";+import { CLIError } from "./errors.js";++/**+ * How a command names an environment for the project it acts on. A legacy+ * project keeps Development and Production and its flags choose between them;+ * a single-mode project has one scope, `default`, and the flags that would+ * pick another are refused locally with the same typed error the API uses.+ */++export const SINGLE_ENVIRONMENT: ProjectEnvironment = "default";++export const LEGACY_ENVIRONMENTS: readonly ProjectEnvironment[] = [+ "development",+ "production",+];++export function projectEnvironments(+ mode: ProjectEnvironmentMode,+): readonly ProjectEnvironment[] {+ return mode === "single" ? [SINGLE_ENVIRONMENT] : LEGACY_ENVIRONMENTS;+}++/** Where `deploy --watch` and CLI sessions land: the working scope of the project. */+export function workingEnvironment(+ mode: ProjectEnvironmentMode,+): ProjectEnvironment {+ return mode === "single" ? SINGLE_ENVIRONMENT : "development";+}++export function singleEnvironmentError(flag: string): CLIError {+ return new CLIError(+ "single_environment_project",+ `${flag} does not apply: this project has a single environment.`,+ `Omit ${flag}. Use a separate project for a distinct development or production target.`,+ );+}++function legacyEnvironment(+ value: string | undefined,+ flag: string,+ fallback: ProjectEnvironment,+): ProjectEnvironment {+ if (!value) return fallback;+ if (value === "development" || value === "production") return value;+ throw new Error(`${flag} must be development or production`);+}++/**+ * The environment a command acts on. Single-mode projects resolve to+ * `default` and refuse any explicit value, including `development`: the CLI+ * knows the project's mode, so unlike an older CLI it has no reason to say it.+ */+export function resolveEnvironment(+ mode: ProjectEnvironmentMode,+ value: string | undefined,+ flag = "--environment",+): ProjectEnvironment {+ if (mode === "single") {+ if (value !== undefined) throw singleEnvironmentError(flag);+ return SINGLE_ENVIRONMENT;+ }+ return legacyEnvironment(value, flag, "development");+}++/** Like `resolveEnvironment`, but a legacy project without a flag means no filter. */+export function resolveEnvironmentFilter(+ mode: ProjectEnvironmentMode,+ value: string | undefined,+ flag = "--environment",+): ProjectEnvironment | undefined {+ if (mode === "single") {+ if (value !== undefined) throw singleEnvironmentError(flag);+ return SINGLE_ENVIRONMENT;+ }+ return value ? legacyEnvironment(value, flag, "development") : undefined;+}++/** The alias a plain `deploy` publishes: `default` for single-mode, `--alias` or Development for legacy. */+export function resolveDeployAlias(+ mode: ProjectEnvironmentMode,+ requestedAlias: string | undefined,+): string {+ if (mode === "single") {+ if (requestedAlias !== undefined) throw singleEnvironmentError("--alias");+ return SINGLE_ENVIRONMENT;+ }+ return requestedAlias ?? "development";+}++/** The user-facing name of a scope; empty for the single scope, which is not spoken of. */+export function environmentLabel(environment: ProjectEnvironment): string {+ return environment === "development"+ ? "Development"+ : environment === "production"+ ? "Production"+ : "";+}diff --git a/cli/src/session-command.test.ts b/cli/src/session-command.test.tsindex 715af53c..c4ac8b91 100644--- a/cli/src/session-command.test.ts+++ b/cli/src/session-command.test.ts@@ -14,6 +14,10 @@ test("sessions target the bound agent's Development deployment", () => {developmentAgentReference("unleash-mcp-test"),"unleash-mcp-test@development",);+ assert.equal(+ developmentAgentReference("unleash-mcp-test", "single"),+ "unleash-mcp-test@default",+ );});test("session shorthand targets the normal create flow", () => {diff --git a/cli/src/session-command.ts b/cli/src/session-command.tsindex f44ca16b..7ebc68e8 100644--- a/cli/src/session-command.ts+++ b/cli/src/session-command.ts@@ -6,7 +6,8 @@ export type SessionAction =| "send"| "end";-import type { MemoryBindings } from "./api.js";+import type { MemoryBindings, ProjectEnvironmentMode } from "./api.js";+import { workingEnvironment } from "./scope.js";export type SessionCommand = {action: SessionAction;@@ -82,8 +83,12 @@ function takeMemoryOptions(args: string[]): MemoryBindings | undefined {return count ? bindings : undefined;}-export function developmentAgentReference(agentId: string): string {- return `${agentId}@development`;+/** The deployment a CLI session runs: the project's working environment. */+export function developmentAgentReference(+ agentId: string,+ mode: ProjectEnvironmentMode = "legacy",+): string {+ return `${agentId}@${workingEnvironment(mode)}`;}export function resolveProjectAgent(diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.tsindex 7aa31425..4b5593c8 100644--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts@@ -1394,6 +1394,7 @@ describe("managed agents proxy", () => {id: "prj_test",slug: "hello-world",name: "Hello World",+ environmentMode: "legacy",environments: [{ name: "development", updatedAt: "2026-08-08" }],agents: [{ id: "hello-world", name: "Hello Hello World" }],createdAt: "2026-08-08",diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.tsindex c1da8fe7..fe1d86e2 100644--- a/cloudflare-workers/api-edge/src/managed_agents.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.ts@@ -608,6 +608,9 @@ function publicProject(value: unknown): Record<string, unknown> {id: project.id,slug: project.slug,name: project.name,+ // Projects that predate the mode column are legacy dual-environment+ // projects; a single-mode project is only ever reported as such.+ environmentMode: project.environmentMode === "single" ? "single" : "legacy",environments: Array.isArray(project.environments)? stripPrivateValues(project.environments): [],@@ -3128,7 +3131,12 @@ export async function handleAgentWebhookInvocation(typeof agentId === "string" &&typeof environment === "string" &&typeof sessionId === "string"- ? `${url.origin}/projects/${encodeURIComponent(projectId)}/sessions/${encodeURIComponent(sessionId)}?agent=${encodeURIComponent(agentId)}&environment=${encodeURIComponent(environment)}`+ ? `${url.origin}/projects/${encodeURIComponent(projectId)}/sessions/${encodeURIComponent(sessionId)}?agent=${encodeURIComponent(agentId)}${+ // The single `default` scope is the dashboard's environmentless URL.+ environment === "default"+ ? ""+ : `&environment=${encodeURIComponent(environment)}`+ }`: undefined;return Response.json({diff --git a/docs/agents/api.mdx b/docs/agents/api.mdxindex 1338ef58..533e27f9 100644--- a/docs/agents/api.mdx+++ b/docs/agents/api.mdx@@ -81,7 +81,7 @@ curl -X POST 'https://app.opencomputer.dev/api/managed-agents/sessions' \| --- | --- || `agentId` | `<agent-id>@development` or `<agent-id>@production`. The alias selects the environment and the deployment active in it. A bare agent ID means `production`. This is how applications address an agent; which deployment runs the session is the platform's choice, recorded on the session. || `deploymentId` | Advanced: pin one deployment instead of resolving an alias, for reproducibility or testing. Send `environment` with it; it may be omitted only when the deployment is promoted to exactly one environment. |-| `environment` | `development` or `production`. Optional with `agentId`; it must agree with the alias. |+| `environment` | `development` or `production` for legacy projects; `default` for single-environment projects. Optional with `agentId`; it must agree with the alias. || `memory` | Bindings keyed by resource ID, at most eight. Needs a deployed agent and an environment. Shapes on [Document memory](/agents/document-memory#session-bindings). || `source` | `api` (default), `playground` or `webhook`. The dashboard groups sessions by it. || `labels` | Your own metadata on the session, an object of strings; see [Labels](#labels). Applied at creation and ignored on a replay of the same `Idempotency-Key`. |@@ -591,15 +591,17 @@ lastEventAt? }`, with `state` one of `awaiting_credentials`,| Operation | Method and path | Success || --- | --- | --- || List projects | `GET /projects` | `200` with `{ projects }` |-| Create project | `POST /projects` with `{ name, slug? }` | `201` with the project |+| Create project | `POST /projects` with `{ name, slug?, environmentMode? }` | `201` with the project. `environmentMode` is `single` (one `default` environment) or `legacy` (Development and Production) || Get project | `GET /projects/<p>` | `200` with `{ project, deployments, sessions, connections, schedules }` || List agents | `GET /agents` | `200` with `{ agents }`: `id`, `name`, `activeAlias`, `activeDeploymentId`, `deploymentCount`; `activeAlias` and `activeDeploymentId` are `null` while the agent has no active deployment || List deployments | `GET /deployments?agentId=<agent-id>` | `200` with `{ deployments }` || Get deployment | `GET /deployments/<id>` | `200` with `id`, `agentId`, `alias`, `memory` declarations, `createdAt` || List GitHub repositories | `GET /projects/<p>/github/repositories?environment=<env>` | `200` with `{ repositories, nextCursor }`; see [GitHub App connections](/agents/github#list-the-repositories-an-environment-can-reach) |-A project is `{ id, slug, name, environments, agents, createdAt, updatedAt }`;-`agents` carries each agent's `id` and `name`. See+A project is `{ id, slug, name, environmentMode, environments, agents, createdAt, updatedAt }`;+`agents` carries each agent's `id` and `name`. Single-environment projects have one+environment named `default`; requests that name `development` resolve to it,+and requests that name `production` fail with `409 single_environment_project`. See[Projects and agents](/agents/projects) for how projects are created andlinked from the CLI.diff --git a/docs/agents/deployments.mdx b/docs/agents/deployments.mdxindex 406b3371..3b33e13c 100644--- a/docs/agents/deployments.mdx+++ b/docs/agents/deployments.mdx@@ -6,7 +6,13 @@ description: "Understand development, production, immutable deployments, and aliA deployment is an immutable build of one agent. An alias gives a stable nameto the deployment clients should run.-Every project starts with two working environments:+New projects have one environment, `default`. Every deploy creates an immutable+deployment and makes it the current one; sessions keep the deployment they+were admitted with. Use separate projects when you need distinct development+and production targets.++Projects created before single-environment mode are legacy projects with two+working environments:| Environment | Alias | How it changes || --- | --- | --- |@@ -16,7 +22,7 @@ Every project starts with two working environments:Sessions keep the deployment they started with. Publishing another versiondoes not change the code underneath an existing session.-## Deploy to production+## Deploy to production (legacy projects)From the project directory:@@ -42,8 +48,14 @@ support@developmentsupport@production```-The project dashboard's environment selector changes which deployment you are-inspecting. The playground has a separate agent selector when a project+Single-environment projects use bare `agent-id` (or `agent-id@default`); older+clients sending `agent-id@development` resolve to the same deployment, while+`agent-id@production` is rejected with `single_environment_project`. Explicit+`--environment` and `--alias` flags are rejected for these projects; `link`+persists the project and `--project` overrides it for one command.++Legacy project dashboards keep the environment selector to change which+deployment you are inspecting. The playground has a separate agent selector when a projectcontains more than one agent.## Review historydiff --git a/docs/agents/schedules.mdx b/docs/agents/schedules.mdxindex b627d939..4bfb9e24 100644--- a/docs/agents/schedules.mdx+++ b/docs/agents/schedules.mdx@@ -45,10 +45,16 @@ Schedules use five-field cron expressions. `timezone` is an IANA timezone suchas `UTC`, `America/Los_Angeles`, or `Europe/London`. The dispatch payload mustbe JSON-compatible and must not contain secrets.-## Development and Production+## Where schedules runWhen `enabled` is omitted, it defaults to `["production"]`.+In a single-environment project, a schedule that enables `production` (or+`default`) runs automatically; one that enables only `development` is+**Manual only**.++### Legacy Development and Production projects+- Development displays every deployed schedule and supports **Run now**.Schedules that do not enable Development are marked **Manual only** and neverrecur there.diff --git a/sdks/typescript/package-lock.json b/sdks/typescript/package-lock.jsonindex 8d124f31..bc2a1d6e 100644--- a/sdks/typescript/package-lock.json+++ b/sdks/typescript/package-lock.json@@ -1,12 +1,12 @@{"name": "@opencomputer/sdk",- "version": "2.3.0",+ "version": "2.3.1","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@opencomputer/sdk",- "version": "2.3.0",+ "version": "2.3.1","license": "MIT","dependencies": {"undici": "^6.0.0 || ^7.0.0"diff --git a/sdks/typescript/package.json b/sdks/typescript/package.jsonindex 29cc98fe..21ba04fd 100644--- a/sdks/typescript/package.json+++ b/sdks/typescript/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/sdk",- "version": "2.3.0",+ "version": "2.3.1","description": "TypeScript SDK for OpenComputer - cloud sandboxes and the Serverless Agents management API","type": "module","main": "dist/index.js",diff --git a/sdks/typescript/src/agents/shapes.ts b/sdks/typescript/src/agents/shapes.tsindex 41307210..26bde28d 100644--- a/sdks/typescript/src/agents/shapes.ts+++ b/sdks/typescript/src/agents/shapes.ts@@ -190,7 +190,7 @@ export const none: Shape<void> = (value, path) => {// ── Sessions ──────────────────────────────────────────────────────────────────-export const environment: Shape<Environment> = oneOf("development", "production");+export const environment: Shape<Environment> = oneOf("default", "development", "production");const labels = record(string);@@ -364,6 +364,7 @@ export const project: Shape<Project> = object({id: string,slug: string,name: string,+ environmentMode: optional(oneOf("single", "legacy")),environments: array(projectEnvironment),agents: array(object({ id: string, name: string })),createdAt: string,diff --git a/sdks/typescript/src/agents/types.ts b/sdks/typescript/src/agents/types.tsindex 4e7a6a6c..75f9d60c 100644--- a/sdks/typescript/src/agents/types.ts+++ b/sdks/typescript/src/agents/types.ts@@ -8,8 +8,14 @@import type { MemoryBindings, SessionMemoryBinding } from "./memory.js";import type { TurnOutcomeDelivery } from "./event-subscriptions.js";-/** Development and Production are separate environments of a project. */-export type Environment = "development" | "production";+/**+ * A project's environment scopes. A single-environment project has one+ * `default` scope; a legacy project has separate Development and Production.+ */+export type Environment = "default" | "development" | "production";++/** How a project scopes its environments; missing on older responses means `legacy`. */+export type ProjectEnvironmentMode = "single" | "legacy";/*** A JSON value: what a turn payload, a tool input or output, and a result@@ -556,6 +562,7 @@ export interface Project {id: string;slug: string;name: string;+ environmentMode?: ProjectEnvironmentMode;environments: ProjectEnvironment[];agents: Array<{ id: string; name: string }>;createdAt: string;@@ -565,6 +572,7 @@ export interface Project {export interface CreateProjectParams {name: string;slug?: string;+ environmentMode?: ProjectEnvironmentMode;}/** What `GET /projects/<p>` returns. */diff --git a/sdks/typescript/src/version.ts b/sdks/typescript/src/version.tsindex 3abc6a8c..d91c9a6a 100644--- a/sdks/typescript/src/version.ts+++ b/sdks/typescript/src/version.ts@@ -27,7 +27,7 @@ export const SDK_VERSION_HEADER = "x-oc-sdk-version";* only failure mode that matters — a stale constant here would silently route a* v2 caller to the old runtime.*/-export const SDK_VERSION = "2.3.0";+export const SDK_VERSION = "2.3.1";/** The identifying header, as a spreadable object. */export function sdkVersionHeaders(): Record<string, string> {diff --git a/web/src/api/client.ts b/web/src/api/client.tsindex c14cd5b7..c855d1da 100644--- a/web/src/api/client.ts+++ b/web/src/api/client.ts@@ -1088,7 +1088,7 @@ export const getModelAccessBindings = (projectId: string) =>export const putModelAccessBinding = (projectId: string,provider: 'anthropic' | 'openai',- environment: 'development' | 'production',+ environment: 'default' | 'development' | 'production',enabled: boolean,) =>apiFetch(@@ -1100,7 +1100,7 @@ export const putModelAccessBinding = (export const deleteModelAccessBinding = (projectId: string,provider: 'anthropic' | 'openai',- environment: 'development' | 'production',+ environment: 'default' | 'development' | 'production',) =>apiFetch<void>(`/v3/projects/${encodeURIComponent(projectId)}/model-access/bindings/${provider}/${environment}`,diff --git a/web/src/components/app-shell.tsx b/web/src/components/app-shell.tsxindex 6beee894..6cef7a25 100644--- a/web/src/components/app-shell.tsx+++ b/web/src/components/app-shell.tsx@@ -64,8 +64,11 @@ import {} from '@/lib/billing-onramp'import { getManagedProject } from '@/managed-agents/api'import {+ projectEnvironmentMode,projectEnvironmentSearch,+ resolveProjectEnvironment,type ProjectEnvironment,+ type ProjectEnvironmentMode,} from '@/managed-agents/project-context'import { managedAgentsNav, type NavGroup } from './app-shell-nav'@@ -158,10 +161,12 @@ function projectIdFromPath(pathname: string): string | undefined {function ManagedProjectContext({projectName,+ mode,environment,onChange,}: {projectName?: string+ mode: ProjectEnvironmentModeenvironment: ProjectEnvironmentonChange: (environment: ProjectEnvironment) => void}) {@@ -173,6 +178,15 @@ function ManagedProjectContext({</div>)}+ // A single-mode project has one scope, so there is nothing to switch.+ if (mode === 'single') {+ return (+ <div className="flex min-w-0 items-center gap-2 font-mono text-sm">+ <span className="text-muted-foreground/50">/</span>+ <span className="truncate font-medium">{projectName}</span>+ </div>+ )+ }return (<div className="flex min-w-0 items-center gap-2 font-mono text-sm"><span className="text-muted-foreground/50">/</span>@@ -636,10 +650,22 @@ export default function AppShell() {queryFn: () => getManagedProject(projectId!),enabled: Boolean(projectId),})- const environment: ProjectEnvironment =- new URLSearchParams(location.search).get('environment') === 'production'- ? 'production'- : 'development'+ const mode = projectEnvironmentMode(project.data?.project)+ const resolved = resolveProjectEnvironment(mode, location.search)+ const environment: ProjectEnvironment = resolved.ok+ ? resolved.environment+ : 'default'+ // An older `?environment=development` bookmark on a single-mode project+ // lands on the environmentless URL once the project's mode is known.+ const canonicalSearch =+ project.data && resolved.ok ? resolved.canonicalSearch : undefined+ useEffect(() => {+ if (canonicalSearch === undefined) return+ void navigate(+ { pathname: location.pathname, search: canonicalSearch },+ { replace: true },+ )+ }, [canonicalSearch, location.pathname, navigate])function changeProjectEnvironment(nextEnvironment: ProjectEnvironment) {void navigate({@@ -662,6 +688,7 @@ export default function AppShell() {<div className="flex min-w-0 items-center px-6"><ManagedProjectContextprojectName={project.data?.project.name}+ mode={mode}environment={environment}onChange={changeProjectEnvironment}/>@@ -700,6 +727,7 @@ export default function AppShell() {{projectId ? (<ManagedProjectContextprojectName={project.data?.project.name}+ mode={mode}environment={environment}onChange={changeProjectEnvironment}/>diff --git a/web/src/managed-agents/BYOK.tsx b/web/src/managed-agents/BYOK.tsxindex bf1e4acb..7b7f214b 100644--- a/web/src/managed-agents/BYOK.tsx+++ b/web/src/managed-agents/BYOK.tsx@@ -16,6 +16,10 @@ import { StatusBadge } from '@/components/status-badge'import { Button } from '@/components/ui/button'import { useAuth } from '@/hooks/useAuth'import { notifyError, notifySuccess } from '@/lib/errors'+import {+ projectEnvironments,+ type ProjectEnvironmentMode,+} from './project-context'import {PLAN_OFFERS,trackUpsellClicked,@@ -39,7 +43,14 @@ import {type ModelRouteProviderChoice,} from './byok-config'-export function ManagedProjectBYOK({ projectId }: { projectId: string }) {+export function ManagedProjectBYOK({+ projectId,+ environmentMode,+}: {+ projectId: string+ environmentMode: ProjectEnvironmentMode+}) {+ const environments = projectEnvironments(environmentMode)const { user } = useAuth()const queryClient = useQueryClient()const [confirmRemoveRoute, setConfirmRemoveRoute] = useState(false)@@ -92,7 +103,7 @@ export function ManagedProjectBYOK({ projectId }: { projectId: string }) {const removeRoute = useMutation({mutationFn: () =>Promise.all(- (['development', 'production'] as const).map((environment) =>+ environments.map((environment) =>deleteManagedModelRoute({ projectId, environment }),),),@@ -112,7 +123,7 @@ export function ManagedProjectBYOK({ projectId }: { projectId: string }) {...(apiProvider === 'openai_compatible' ? { baseUrl } : {}),})return Promise.all(- (['development', 'production'] as const).map((environment) =>+ environments.map((environment) =>putManagedModelRoute({projectId,environment,diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsxindex 6a5f3219..c1c938df 100644--- a/web/src/managed-agents/Detail.tsx+++ b/web/src/managed-agents/Detail.tsx@@ -84,7 +84,9 @@ import { isNearScrollEnd } from './scroll-follow'import { createStartCommand, starterCommands } from './onboarding'import {projectContextSearch,+ projectEnvironmentMode,requestedProjectAgentId,+ resolveProjectEnvironment,} from './project-context'import {playgroundSessionIdFromSearch,@@ -658,10 +660,14 @@ export default function ManagedAgentDetail({? routeTab: 'playground': standaloneTab- const environment =- searchParams.get('environment') === 'production'- ? 'production'- : 'development'+ const environmentMode = projectEnvironmentMode(project?.project)+ const resolvedEnvironment = resolveProjectEnvironment(+ environmentMode,+ searchParams.toString(),+ )+ const environment = resolvedEnvironment.ok+ ? resolvedEnvironment.environment+ : 'default'const requestedPlaygroundId = playgroundSessionIdFromSearch(location.search)const firstRunPrompt = templateFirstRunPrompt(location.state)const [newSessionKey, setNewSessionKey] = useState(() => crypto.randomUUID())@@ -924,6 +930,43 @@ export default function ManagedAgentDetail({...(project ? ([{ id: 'byok', label: 'BYOK' }] as const) : []),]+ if (project && !resolvedEnvironment.ok) {+ return (+ <div className="space-y-5">+ <PageHeader+ title={project.project.name}+ description="Single environment"+ />+ <Panel>+ <EmptyState+ icon={Bot}+ title="This project has a single environment"+ description={`“${resolvedEnvironment.requested}” is not an environment of this project (single_environment_project). Use a separate project for a distinct ${resolvedEnvironment.requested} target.`}+ action={+ <Button asChild variant="outline" size="sm">+ <Link+ to={{+ pathname: location.pathname,+ search: projectContextSearch(+ location.search,+ requestedProjectAgentId(+ location.search,+ project.project.agents,+ ),+ 'default',+ ),+ }}+ >+ Open the project+ </Link>+ </Button>+ }+ />+ </Panel>+ </div>+ )+ }+return (<divclassName={cn(@@ -939,7 +982,7 @@ export default function ManagedAgentDetail({}description={project- ? `${project.project.agents.length} ${project.project.agents.length === 1 ? 'agent' : 'agents'} · development and production environments`+ ? `${project.project.agents.length} ${project.project.agents.length === 1 ? 'agent' : 'agents'}${environmentMode === 'legacy' ? ' · development and production environments' : ''}`: activeDeployment.data? `Active deployment · ${activeDeployment.data.alias}`: 'Loading active deployment…'@@ -1073,7 +1116,11 @@ export default function ManagedAgentDetail({<EmptyStateicon={Bot}title="Deploy the hello-world agent to use Debug playground"- description={`Create the starter locally, then sync it directly to ${environment}.`}+ description={+ environmentMode === 'single'+ ? 'Create the starter locally, then sync it to this project.'+ : `Create the starter locally, then sync it directly to ${environment}.`+ }action={<div className="flex max-w-xl flex-col items-center gap-3"><pre className="bg-foreground text-background max-w-full overflow-x-auto rounded-md px-4 py-3 text-left text-xs leading-6">@@ -1378,7 +1425,10 @@ export default function ManagedAgentDetail({) : null}{activeTab === 'byok' && project ? (- <ManagedProjectBYOK projectId={project.project.id} />+ <ManagedProjectBYOK+ projectId={project.project.id}+ environmentMode={environmentMode}+ />) : null}{activeTab === 'connections' && project ? (diff --git a/web/src/managed-agents/GitHub.tsx b/web/src/managed-agents/GitHub.tsxindex ca54b76f..e403c0ba 100644--- a/web/src/managed-agents/GitHub.tsx+++ b/web/src/managed-agents/GitHub.tsx@@ -27,7 +27,7 @@ export function ManagedProjectGitHub({environment,}: {projectId: string- environment: 'development' | 'production'+ environment: 'default' | 'development' | 'production'}) {const queryClient = useQueryClient()const [selectedConnectionId, setSelectedConnectionId] = useState('')diff --git a/web/src/managed-agents/Home.tsx b/web/src/managed-agents/Home.tsxindex c7ca55e1..bb888d2e 100644--- a/web/src/managed-agents/Home.tsx+++ b/web/src/managed-agents/Home.tsx@@ -121,7 +121,9 @@ export default function ProjectsHome() {<p className="text-muted-foreground mt-0.5 text-xs">{project.agents.length}{' '}{project.agents.length === 1 ? 'agent' : 'agents'} ·{' '}- {project.environments.length} environments+ {project.environments.length === 1+ ? 'single environment'+ : `${project.environments.length} environments`}</p></div><Buttondiff --git a/web/src/managed-agents/ModelAccessCallback.tsx b/web/src/managed-agents/ModelAccessCallback.tsxindex 8550b77c..cf8df46a 100644--- a/web/src/managed-agents/ModelAccessCallback.tsx+++ b/web/src/managed-agents/ModelAccessCallback.tsx@@ -3,7 +3,12 @@ import { CheckCircle2, CircleAlert, Loader2 } from 'lucide-react'import { Link, useNavigate, useSearchParams } from 'react-router-dom'import { Panel, PanelContent } from '@/components/panel'import { Button } from '@/components/ui/button'-import { completeManagedModelAccess, putManagedModelAccessBinding } from './api'+import {+ completeManagedModelAccess,+ getManagedProject,+ putManagedModelAccessBinding,+} from './api'+import { projectEnvironmentMode, projectEnvironments } from './project-context'import {MODEL_ACCESS_PROJECT_KEY,MODEL_ACCESS_RETURN_TO_KEY,@@ -39,14 +44,16 @@ export default function ModelAccessCallback() {.then(async () => {const projectId = sessionStorage.getItem(MODEL_ACCESS_PROJECT_KEY)if (projectId) {+ const { project } = await getManagedProject(projectId)await Promise.all(- (['development', 'production'] as const).map((environment) =>- putManagedModelAccessBinding({- projectId,- provider: 'openai',- environment,- enabled: true,- }),+ projectEnvironments(projectEnvironmentMode(project)).map(+ (environment) =>+ putManagedModelAccessBinding({+ projectId,+ provider: 'openai',+ environment,+ enabled: true,+ }),),)}diff --git a/web/src/managed-agents/Schedules.tsx b/web/src/managed-agents/Schedules.tsxindex 7d51f3d9..f0821aee 100644--- a/web/src/managed-agents/Schedules.tsx+++ b/web/src/managed-agents/Schedules.tsx@@ -41,7 +41,7 @@ export function ManagedAgentSchedules({}: {projectId: stringagentId: string- environment: 'development' | 'production'+ environment: 'default' | 'development' | 'production'deployed: boolean}) {const queryClient = useQueryClient()@@ -186,7 +186,9 @@ export function ManagedAgentSchedules({<PanelDescription>{environment === 'development'? 'Development schedules run only when you choose Run now.'- : 'Production schedules run automatically. Each run starts a fresh session.'}+ : environment === 'default'+ ? 'Enabled schedules run automatically. Each run starts a fresh session.'+ : 'Production schedules run automatically. Each run starts a fresh session.'}</PanelDescription></div></PanelHeader>diff --git a/web/src/managed-agents/Secrets.tsx b/web/src/managed-agents/Secrets.tsxindex 95e7e9a0..ce54215d 100644--- a/web/src/managed-agents/Secrets.tsx+++ b/web/src/managed-agents/Secrets.tsx@@ -21,7 +21,7 @@ import {putManagedProjectSecret,} from './api'-type Environment = 'development' | 'production'+type Environment = 'default' | 'development' | 'production'function parseOrigins(value: string) {return [...new Set(value.split(/[\s,]+/).map((part) => part.trim()))].filter(diff --git a/web/src/managed-agents/Slack.tsx b/web/src/managed-agents/Slack.tsxindex ac6ae79b..a57a7160 100644--- a/web/src/managed-agents/Slack.tsx+++ b/web/src/managed-agents/Slack.tsx@@ -68,7 +68,7 @@ import {} from './slack-setup'import { ManagedSlackWizard } from './SlackWizard'-type Environment = 'development' | 'production'+type Environment = 'default' | 'development' | 'production'/*** Slack's consent page opens in this tab. The platform brings the browserdiff --git a/web/src/managed-agents/Webhooks.tsx b/web/src/managed-agents/Webhooks.tsxindex ea3fed19..ea27d059 100644--- a/web/src/managed-agents/Webhooks.tsx+++ b/web/src/managed-agents/Webhooks.tsx@@ -60,7 +60,7 @@ export function ManagedAgentWebhooks({projectId: stringagentId: stringagentName: string- environment: 'development' | 'production'+ environment: 'default' | 'development' | 'production'deployed: boolean}) {const queryClient = useQueryClient()@@ -274,7 +274,9 @@ export function ManagedAgentWebhooks({/></div><div className="space-y-2">- <Label htmlFor="webhook-identity">Delivery identity (optional)</Label>+ <Label htmlFor="webhook-identity">+ Delivery identity (optional)+ </Label><Inputid="webhook-identity"value={identity}@@ -284,8 +286,8 @@ export function ManagedAgentWebhooks({/><p className="text-muted-foreground text-xs">Where a delivery's identity is read when the sender sets no- Idempotency-Key, so a provider's retry does not start a second- session. A header name, or a JSON Pointer into the body.+ Idempotency-Key, so a provider's retry does not start a+ second session. A header name, or a JSON Pointer into the body.</p></div><DialogFooter>diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.tsindex d572fee5..5ca008b9 100644--- a/web/src/managed-agents/api.ts+++ b/web/src/managed-agents/api.ts@@ -92,7 +92,9 @@ const deploymentSchema = z.object({agentId: z.string(),cron: z.string(),timezone: z.string(),- enabled: z.array(z.enum(['development', 'production'])),+ enabled: z.array(+ z.enum(['default', 'development', 'production']),+ ),overlap: z.enum(['skip', 'allow']),dispatch: z.object({text: z.string().optional(),@@ -124,9 +126,10 @@ const projectSchema = z.object({id: z.string(),slug: z.string(),name: z.string(),+ environmentMode: z.enum(['single', 'legacy']).optional().default('legacy'),environments: z.array(z.object({- name: z.enum(['development', 'production']),+ name: z.enum(['default', 'development', 'production']),agentId: z.string().optional(),activeDeploymentId: z.string().optional(),updatedAt: z.string(),@@ -148,7 +151,7 @@ const databaseResultSchema = z.object({truncated: z.boolean(),})const databaseQueryResponseSchema = z.object({- environment: z.enum(['development', 'production']),+ environment: z.enum(['default', 'development', 'production']),result: databaseResultSchema,})@@ -228,7 +231,7 @@ const templateInstallationSchema = z.object({const secretSchema = z.object({name: z.string(),projectId: z.string(),- environment: z.enum(['development', 'production']),+ environment: z.enum(['default', 'development', 'production']),agentId: z.string().optional(),allowedOrigins: z.array(z.string()),createdAt: z.string(),@@ -278,7 +281,7 @@ const modelAccessConnectResponseSchema = z.object({const modelAccessBindingSchema = z.object({projectId: z.string(),- environment: z.enum(['development', 'production']),+ environment: z.enum(['default', 'development', 'production']),provider: z.enum(['anthropic', 'openai']),connectionId: z.string(),enabled: z.boolean(),@@ -293,7 +296,7 @@ const modelAccessBindingsResponseSchema = z.object({const projectModelRouteSchema = z.object({id: z.string(),projectId: z.string(),- environment: z.enum(['development', 'production']),+ environment: z.enum(['default', 'development', 'production']),agentId: z.string().nullish(),connectionId: z.string(),model: z.string(),@@ -310,7 +313,7 @@ const modelRoutesResponseSchema = z.object({const runtimeVariableSchema = z.object({name: z.string(),projectId: z.string(),- environment: z.enum(['development', 'production']),+ environment: z.enum(['default', 'development', 'production']),agentId: z.string().optional(),createdAt: z.string(),updatedAt: z.string(),@@ -334,7 +337,7 @@ const githubInstallationSchema = z.object({const githubStatusSchema = z.object({environments: z.array(z.object({- environment: z.enum(['development', 'production']),+ environment: z.enum(['default', 'development', 'production']),state: z.enum(['not_connected', 'active', 'suspended', 'deleted']),installation: githubInstallationSchema.optional(),}),@@ -424,7 +427,7 @@ const slackSetupSchema = z.object({requestKey: z.string(),projectId: z.string(),agentId: z.string(),- alias: z.enum(['development', 'production']),+ alias: z.enum(['default', 'development', 'production']),channelId: z.string(),name: z.string(),connectionId: z.string(),@@ -557,7 +560,7 @@ const channelsResponseSchema = z.object({const scheduleSchema = z.object({id: z.string(),projectId: z.string(),- environment: z.enum(['development', 'production']),+ environment: z.enum(['default', 'development', 'production']),agentId: z.string(),deploymentId: z.string(),cron: z.string(),@@ -576,7 +579,7 @@ const scheduleRunSchema = z.object({id: z.string(),scheduleId: z.string(),projectId: z.string(),- environment: z.enum(['development', 'production']),+ environment: z.enum(['default', 'development', 'production']),deploymentId: z.string(),scheduledAt: z.string(),manual: z.boolean(),@@ -596,7 +599,7 @@ const scheduleRunResponseSchema = z.object({ run: scheduleRunSchema })const webhookSchema = z.object({id: z.string(),projectId: z.string(),- environment: z.enum(['development', 'production']),+ environment: z.enum(['default', 'development', 'production']),agentId: z.string(),name: z.string(),enabled: z.boolean(),@@ -733,7 +736,10 @@ const sessionSummarySchema = z.object({projectId: z.string(),agentId: z.string(),deploymentId: z.string(),- environment: z.enum(['development', 'production']).nullable().default(null),+ environment: z+ .enum(['default', 'development', 'production'])+ .nullable()+ .default(null),source: z.enum(['api', 'channel', 'playground', 'schedule', 'webhook']).optional()@@ -1000,7 +1006,7 @@ export type ManagedDatabaseResult = z.infer<typeof databaseResultSchema>export async function queryManagedProjectDatabase(input: {projectId: string- environment: 'development' | 'production'+ environment: 'default' | 'development' | 'production'sql: stringparameters?: Array<string | number | boolean | null>}) {@@ -1030,7 +1036,7 @@ export async function getManagedGitHubStatus(projectId: string) {export async function connectManagedGitHub(input: {projectId: string- environments: Array<'development' | 'production'>+ environments: Array<'default' | 'development' | 'production'>}) {return apiFetch(`/managed-agents/projects/${encodeURIComponent(input.projectId)}/github/connect`,@@ -1057,7 +1063,7 @@ export async function addManagedGitHubConnection(mode: 'install' | 'existing') {export async function attachManagedGitHub(input: {projectId: string- environment: 'development' | 'production'+ environment: 'default' | 'development' | 'production'connectionId: string}) {return apiFetch(@@ -1075,7 +1081,7 @@ export async function attachManagedGitHub(input: {export async function disconnectManagedGitHub(input: {projectId: string- environment: 'development' | 'production'+ environment: 'default' | 'development' | 'production'}) {return apiFetch<void>(`/managed-agents/projects/${encodeURIComponent(input.projectId)}/github?environment=${input.environment}`,@@ -1145,7 +1151,7 @@ export async function getManagedModelRoutes(projectId: string) {export async function putManagedModelRoute(input: {projectId: string- environment: 'development' | 'production'+ environment: 'default' | 'development' | 'production'connectionId: stringmodel: stringfallback: 'fail' | 'managed'@@ -1168,7 +1174,7 @@ export async function putManagedModelRoute(input: {export async function deleteManagedModelRoute(input: {projectId: string- environment: 'development' | 'production'+ environment: 'default' | 'development' | 'production'agentId?: string}) {return apiFetch<void>(@@ -1221,7 +1227,7 @@ export async function getManagedModelAccessBindings(projectId: string) {export async function putManagedModelAccessBinding(input: {projectId: stringprovider: 'anthropic' | 'openai'- environment: 'development' | 'production'+ environment: 'default' | 'development' | 'production'enabled: boolean}) {return apiFetch(@@ -1233,7 +1239,7 @@ export async function putManagedModelAccessBinding(input: {export async function getManagedProjectSecrets(projectId: string,- environment: 'development' | 'production',+ environment: 'default' | 'development' | 'production',) {return (await apiFetch(@@ -1246,7 +1252,7 @@ export async function getManagedProjectSecrets(export async function putManagedProjectSecret(input: {projectId: string- environment: 'development' | 'production'+ environment: 'default' | 'development' | 'production'agentId?: stringname: stringvalue: string@@ -1269,7 +1275,7 @@ export async function putManagedProjectSecret(input: {export async function deleteManagedProjectSecret(input: {projectId: string- environment: 'development' | 'production'+ environment: 'default' | 'development' | 'production'agentId?: stringname: string}) {@@ -1283,7 +1289,7 @@ export async function deleteManagedProjectSecret(input: {export async function getAgentRuntimeVariables(projectId: string,- environment: 'development' | 'production',+ environment: 'default' | 'development' | 'production',) {return (await apiFetch(@@ -1296,7 +1302,7 @@ export async function getAgentRuntimeVariables(export async function putAgentRuntimeVariable(input: {projectId: string- environment: 'development' | 'production'+ environment: 'default' | 'development' | 'production'agentId?: stringname: stringvalue: string@@ -1317,7 +1323,7 @@ export async function putAgentRuntimeVariable(input: {export async function deleteAgentRuntimeVariable(input: {projectId: string- environment: 'development' | 'production'+ environment: 'default' | 'development' | 'production'agentId?: stringname: string}) {@@ -1403,7 +1409,7 @@ export async function getManagedAgentChannels() {export async function getManagedAgentSchedules(projectId: string,agentId: string,- environment: 'development' | 'production',+ environment: 'default' | 'development' | 'production',) {const query = new URLSearchParams({ projectId, agentId, environment })return (@@ -1418,7 +1424,7 @@ export async function getManagedAgentSchedules(export async function getManagedAgentScheduleRuns(projectId: string,agentId: string,- environment: 'development' | 'production',+ environment: 'default' | 'development' | 'production',) {const query = new URLSearchParams({ projectId, agentId, environment })return (@@ -1433,7 +1439,7 @@ export async function getManagedAgentScheduleRuns(export async function runManagedAgentSchedule(projectId: string,agentId: string,- environment: 'development' | 'production',+ environment: 'default' | 'development' | 'production',scheduleId: string,) {const query = new URLSearchParams({ projectId, agentId, environment })@@ -1449,7 +1455,7 @@ export async function runManagedAgentSchedule(export async function getManagedAgentWebhooks(projectId: string,agentId: string,- environment: 'development' | 'production',+ environment: 'default' | 'development' | 'production',) {const query = new URLSearchParams({ agentId, environment })return (@@ -1464,7 +1470,7 @@ export async function getManagedAgentWebhooks(export async function createManagedAgentWebhook(input: {projectId: stringagentId: string- environment: 'development' | 'production'+ environment: 'default' | 'development' | 'production'name: stringidentity?: string}) {@@ -1569,7 +1575,7 @@ export async function completeManagedAgentSlack(export type ManagedSlackSetupTarget = {agentId: string- alias: 'development' | 'production'+ alias: 'default' | 'development' | 'production'channelId?: string}@@ -2172,7 +2178,7 @@ export async function getManagedAgentSession(sessionId: string) {)}-export type ManagedMemoryEnvironment = 'development' | 'production'+export type ManagedMemoryEnvironment = 'default' | 'development' | 'production'/** The complete address of one document; every read and write names it in full. */export type ManagedMemoryDocumentTarget = {diff --git a/web/src/managed-agents/project-context.test.ts b/web/src/managed-agents/project-context.test.tsindex 79620769..5a31fad0 100644--- a/web/src/managed-agents/project-context.test.ts+++ b/web/src/managed-agents/project-context.test.ts@@ -1,8 +1,11 @@import { describe, expect, it } from 'vitest'import {projectContextSearch,+ projectEnvironmentMode,projectEnvironmentSearch,+ projectEnvironments,requestedProjectAgentId,+ resolveProjectEnvironment,selectedProjectAgentId,} from './project-context'@@ -61,4 +64,54 @@ describe('managed project context', () => {),).toBe('?agent=support')})++ it('reads a project without a stored mode as legacy', () => {+ expect(projectEnvironmentMode(undefined)).toBe('legacy')+ expect(projectEnvironmentMode({})).toBe('legacy')+ expect(projectEnvironmentMode({ environmentMode: 'single' })).toBe('single')+ expect(projectEnvironments('legacy')).toEqual(['development', 'production'])+ expect(projectEnvironments('single')).toEqual(['default'])+ })++ it('resolves legacy environments from the query', () => {+ expect(resolveProjectEnvironment('legacy', '')).toEqual({+ ok: true,+ environment: 'development',+ })+ expect(+ resolveProjectEnvironment('legacy', '?environment=production'),+ ).toEqual({ ok: true, environment: 'production' })+ })++ it('redirects an older development bookmark on a single-mode project', () => {+ expect(resolveProjectEnvironment('single', '?agent=support')).toEqual({+ ok: true,+ environment: 'default',+ })+ expect(+ resolveProjectEnvironment(+ 'single',+ '?agent=support&environment=development',+ ),+ ).toEqual({+ ok: true,+ environment: 'default',+ canonicalSearch: '?agent=support',+ })+ })++ it('reports production as incompatible with a single-mode project', () => {+ expect(+ resolveProjectEnvironment('single', '?environment=production'),+ ).toEqual({ ok: false, requested: 'production' })+ })++ it('keeps single-mode URLs environmentless', () => {+ expect(+ projectContextSearch('?environment=production', 'a', 'default'),+ ).toBe('?agent=a')+ expect(+ projectEnvironmentSearch('?environment=development', 'default'),+ ).toBe('')+ })})diff --git a/web/src/managed-agents/project-context.ts b/web/src/managed-agents/project-context.tsindex 8ebd0753..b2b9a44c 100644--- a/web/src/managed-agents/project-context.ts+++ b/web/src/managed-agents/project-context.ts@@ -1,4 +1,58 @@-export type ProjectEnvironment = 'development' | 'production'+export type ProjectEnvironment = 'default' | 'development' | 'production'+export type ProjectEnvironmentMode = 'single' | 'legacy'++export const SINGLE_ENVIRONMENT: ProjectEnvironment = 'default'+export const LEGACY_ENVIRONMENTS = ['development', 'production'] as const++/** A project without a stored mode is a legacy Development/Production project. */+export function projectEnvironmentMode(+ project: { environmentMode?: string } | undefined,+): ProjectEnvironmentMode {+ return project?.environmentMode === 'single' ? 'single' : 'legacy'+}++export function projectEnvironments(+ mode: ProjectEnvironmentMode,+): readonly ProjectEnvironment[] {+ return mode === 'single' ? [SINGLE_ENVIRONMENT] : LEGACY_ENVIRONMENTS+}++export type ResolvedProjectEnvironment =+ | { ok: true; environment: ProjectEnvironment; canonicalSearch?: string }+ | { ok: false; requested: string }++/**+ * Resolve the `?environment=` query for a project. Legacy projects read+ * Development unless Production is asked for. Single-mode projects have one+ * `default` scope: an older `environment=development` bookmark resolves to it+ * and reports the environmentless URL to redirect to; `environment=production`+ * is incompatible and is reported rather than shown as the single scope.+ */+export function resolveProjectEnvironment(+ mode: ProjectEnvironmentMode,+ search: string,+): ResolvedProjectEnvironment {+ const params = new URLSearchParams(search)+ const requested = params.get('environment')+ if (mode === 'legacy') {+ return {+ ok: true,+ environment: requested === 'production' ? 'production' : 'development',+ }+ }+ if (requested === null || requested === '' || requested === 'default') {+ return { ok: true, environment: SINGLE_ENVIRONMENT }+ }+ if (requested === 'development') {+ params.delete('environment')+ return {+ ok: true,+ environment: SINGLE_ENVIRONMENT,+ canonicalSearch: params.size ? `?${params.toString()}` : '',+ }+ }+ return { ok: false, requested }+}export function projectAgentIdFromPath(pathname: string) {const match = pathname.match(@@ -34,6 +88,15 @@ export function requestedProjectAgentId(return agents.find((agent) => agent.id === requested)?.id}+/**+ * The project's working scope (legacy Development, single `default`) is the+ * URL default and is never written to the query, so single-mode URLs stay+ * environmentless and cross-project links carry no legacy environment.+ */+function isUrlDefault(environment: ProjectEnvironment) {+ return environment === 'development' || environment === 'default'+}+export function projectContextSearch(search: string,agentId: string | undefined,@@ -42,7 +105,7 @@ export function projectContextSearch(const next = new URLSearchParams(search)if (agentId) next.set('agent', agentId)else next.delete('agent')- if (environment === 'development') next.delete('environment')+ if (isUrlDefault(environment)) next.delete('environment')else next.set('environment', environment)return next.size ? `?${next.toString()}` : ''}@@ -52,7 +115,7 @@ export function projectEnvironmentSearch(environment: ProjectEnvironment,) {const next = new URLSearchParams(search)- if (environment === 'development') next.delete('environment')+ if (isUrlDefault(environment)) next.delete('environment')else next.set('environment', environment)return next.size ? `?${next.toString()}` : ''}diff --git a/web/src/managed-agents/slack-setup.test.ts b/web/src/managed-agents/slack-setup.test.tsindex 9ddff387..beddb934 100644--- a/web/src/managed-agents/slack-setup.test.ts+++ b/web/src/managed-agents/slack-setup.test.ts@@ -19,6 +19,7 @@ const project: ManagedProjectOverview['project'] = {id: 'prj_1',slug: 'slack-coder',name: 'slack-coder',+ environmentMode: 'legacy',environments: [{name: 'development',diff --git a/web/src/managed-agents/slack-setup.ts b/web/src/managed-agents/slack-setup.tsindex 03942a07..cf9efcc5 100644--- a/web/src/managed-agents/slack-setup.ts+++ b/web/src/managed-agents/slack-setup.ts@@ -454,7 +454,7 @@ export function slackSlotsForEnvironment(input: {project: ManagedProjectOverview['project']deployments: ManagedAgentDeployment[]channels: ManagedAgentChannel[]- environment: 'development' | 'production'+ environment: 'default' | 'development' | 'production'}): SlackSlot[] {const projectAgentIds = new Set(input.project.agents.map((agent) => agent.id))const live = input.channels.filter(