import { CliError, type CommandContext, ExitCode, type ImmediateCommand } from '@agentic-kit/command'; import { PROJECT_FILE, readProjectFile } from '@agentic-kit/db-tools'; import { appAuthEndpoint, type AppSession, appSignIn, appSignOut, loadAppSession, SignInError } from '@agentic-kit/session'; import { z } from 'zod'; import type { CliCode } from '../errors'; import { type ActiveBackend, activeBackend, AS_PERSON, CLI_NAME, CODE_STDIN, openSession, PASSWORD_STDIN, personOnly, type Session, signInFailed, signInSteps, withSignInProof } from '../session'; /** The app this directory is bound to: its database, the context its sign-in is kept under, and that sign-in, if any. */ export type BoundApp = { database: { id: string; name: string }; context: string; backend: ActiveBackend; signIn: AppSession | null }; /** * The app of the database bound to `ctx.cwd`, on the backend of `session`. An app sign-in is kept under a stored * context, so a backend the environment gives has none. */ export async function boundApp(session: Session, ctx: CommandContext): Promise { const backend = activeBackend(session); if (!backend) { throw new CliError({ code: 'no-backend', message: 'No Constructive backend is chosen, so there is no app to sign in to.', hint: 'Sign in to a backend first.', next: signInSteps(session) }); } if (!session.context) { throw new CliError({ code: 'invalid-input', message: 'The backend of this run comes from the environment, and an app sign-in is kept under a stored context, so there is none to use.', hint: `Unset the CONSTRUCTIVE_* endpoint variables and run "${CLI_NAME} context use ", or add the backend with "${CLI_NAME} context add".`, exitCode: ExitCode.usage }); } const file = await readProjectFile(ctx.cwd); if (file.kind === 'failed') { throw new CliError({ code: 'invalid-binding', message: file.failure.message, hint: file.failure.hint, exitCode: ExitCode.usage, details: { file: PROJECT_FILE } }); } const database = file.value?.database; if (!database?.name) { throw new CliError({ code: 'not-bound', message: database ? `The binding in ${PROJECT_FILE} names no database name, so the app's endpoints can't be found.` : 'This directory is not bound to a database, so it has no app.', hint: `Bind it with "${CLI_NAME} db use " or "${CLI_NAME} db create ".`, next: [ctx.next(['db', 'use', { placeholder: 'name-or-id' }], 'Bind this directory to a database you already have'), ctx.next(['db', 'list'], 'See the databases this account has')] }); } return { database: { id: database.id, name: database.name }, context: session.context, backend, signIn: loadAppSession(session.store, session.context, database.id) }; } const AppLoginInput = z.object({ email: z.string().describe("Email of an account of the app: one of the app's own users, not your Constructive account"), ...PASSWORD_STDIN, ...CODE_STDIN }); type AppLoginData = { database: { id: string; name: string }; account: { userId: string; email: string }; expiresAt?: string }; const appLogin: ImmediateCommand = { name: 'app login', summary: 'Sign in to the app of this directory', description: "Signs in to the app of the database bound to this directory, as one of the app's own users, and keeps the sign-in in your store for that database. " + "The records commands, the record tools of mcp and api with --plane app act as that user, under the app's own row rules. " + 'The password comes from a prompt on a terminal, or from stdin with --password-stdin, never from a flag; a second factor, as login takes it.', effect: 'write', immediate: true, input: AppLoginInput, examples: [{ command: `printf %s "$APP_PASSWORD" | ${CLI_NAME} app login --email buyer@example.com --password-stdin`, description: 'From a script or an agent' }], async run(input, ctx) { personOnly(ctx, 'app login'); const session = await openSession(ctx); const app = await boundApp(session, ctx); const step = { store: session.store, context: app.context, authEndpoint: appAuthEndpoint(app.backend, app.database.name), email: input.email, command: 'app login', prompt: 'App password', cause: `the app ${app.database.name}` }; let signedIn: AppSession; try { signedIn = await withSignInProof(ctx, input, step, (proof) => appSignIn({ store: session.store, context: app.context, backend: app.backend, database: app.database, email: input.email, ...proof })); } catch (error) { if (error instanceof SignInError) throw signInFailed(error); throw error; } const data: AppLoginData = { database: app.database, account: { userId: signedIn.userId, email: signedIn.email }, ...(signedIn.accessTokenExpiresAt ? { expiresAt: signedIn.accessTokenExpiresAt } : {}) }; return { data, text: `Signed in to the app ${app.database.name} as ${signedIn.email}.${data.expiresAt ? ` The sign-in ends ${data.expiresAt}.` : ''}`, next: [ ctx.next(['records', 'add', { placeholder: 'table' }, '--records', { placeholder: 'json' }], 'Add rows as this user', AS_PERSON), ctx.next(['api', 'query', { placeholder: 'query' }, '--plane', 'app'], 'Read rows as this user', AS_PERSON) ] }; } }; const appLogout: ImmediateCommand>, { database: { id: string; name: string }; signedOut: boolean }> = { name: 'app logout', summary: 'Sign out of the app of this directory', description: "Ends the app sign-in of the database bound to this directory on the app's server, and removes it from your store.", effect: 'write', immediate: true, input: z.object({}), async run(_input, ctx) { personOnly(ctx, 'app logout'); const session = await openSession(ctx); const app = await boundApp(session, ctx); const signedOut = await appSignOut({ store: session.store, context: app.context, backend: app.backend, databaseId: app.database.id }); return { data: { database: app.database, signedOut }, text: signedOut ? `Signed out of the app ${app.database.name}.` : `No one is signed in to the app ${app.database.name}; nothing changed.` }; } }; export const appCommands = [appLogin, appLogout];