different-ai/openwork · error

organization_context_required (Error; HTTP 500 unless…

Error message

organization_context_required (Error; HTTP 500 unless caught by route handler middleware)

What it means

The contextFor helper in codemode-scripts routes requires the Hono context to carry an organizationContext variable set by upstream org middleware. If it is missing, a plain Error("organization_context_required") is thrown; per the message this surfaces as HTTP 500 unless the route handler middleware catches it. It is an internal invariant: the route was reached without the org middleware having resolved the organization/session.

Solutions

  1. Mount these routes inside the same middleware chain that sets organizationContext (org auth middleware) so the variable is always present.
  2. Verify the middleware registration order: organization-context middleware must execute before codemode-scripts handlers.
  3. Catch/convert the error in route middleware to return 401/403 instead of a 500 for unauthenticated access.
  4. In tests, run requests through the full app with middleware rather than calling handlers directly.

Example fix

// before
app.route("/org/codemode-scripts", codemodeScriptRoutes) // no org middleware
// after
app.use("/org/*", organizationContextMiddleware)
app.route("/org/codemode-scripts", codemodeScriptRoutes)
Defensive patterns

Strategy: try-catch

Validate before calling

// before calling routes or inside the handler
const organizationContext = c.get("organizationContext")
if (!organizationContext) {
  return c.json({ error: "organization_context_required" }, 401)
}

Type guard

function hasOrganizationContext(c: { get(name: "organizationContext"): unknown }): boolean {
  return c.get("organizationContext") !== undefined && c.get("organizationContext") !== null
}

Try / catch

try {
  return await contextFor(c)
} catch (e) {
  if (e instanceof Error && e.message === "organization_context_required") {
    return c.json({ error: "organization_context_required" }, 401)
  }
  throw e
}

Prevention

When it happens

Trigger: Any codemode script route handler calling contextFor when c.get("organizationContext") is undefined — i.e. the organization-context middleware did not run, did not match the route, or failed silently before this handler.

Common situations: Registering the codemode-scripts routes outside the middleware chain that sets organizationContext; middleware short-circuiting on auth failure without halting; a route path added before the middleware's route matcher; tests invoking handlers directly without the middleware.

Understand the failure class

Related errors


AI-assisted analysis of different-ai/openwork@2b7df46e8a (2026-09-01). Data as JSON: /api/errors/873857f8625cabb0. Report an issue: GitHub.

Appendix: source

Thrown at ee/apps/den-api/src/routes/org/codemode-scripts.ts:159

      body: {
        error: message,
        message: "Run the exact procedure successfully with execute_capability_script, then retry saving the Workflow without changing the code. The successful run must be less than 15 minutes old.",
      },
    } as const
  }
  return { status: 400, body: { error: "workflow_rejected", message } } as const
}

export const saveWorkflowOperationId = "saveWorkflow"

export function registerOrgWorkflowRoutes<T extends { Variables: OrgRouteVariables }>(app: Hono<T>) {
  const contextFor = async (c: {
    get(name: "organizationContext"): OrgRouteVariables["organizationContext"]
    get(name: "session"): OrgRouteVariables["session"]
    env: unknown
  }) => {
    const context = c.get("organizationContext")
    if (!context) throw new Error("organization_context_required")
    const teams = await listTeamsForMember({ organizationId: context.organization.id, memberId: context.currentMember.id })
    const member = { orgMembershipId: context.currentMember.id, teamIds: teams.map((team) => team.id) }
    const catalog = await getCatalog(app as unknown as Hono, c.env)
    const principal = {
      userId: context.currentMember.userId,
      organizationId: context.organization.id,
      scopes: new Set(DEN_MCP_REQUESTED_SCOPES),
      payload: {},
    }
    const capabilityContext = createCapabilityRegistryContext({
      app: app as unknown as Hono,
      env: c.env,
      catalog,
      principal,
      organizationId: context.organization.id,
      member,
      redirectUriBase: env.apiPublicUrl ?? "http://127.0.0.1",
      generatedArtifactViewsEnabled: env.generatedArtifactViewsEnabled,

View on GitHub (pinned to 2b7df46e8a)