Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
249 changes: 75 additions & 174 deletions TODO.md

Large diffs are not rendered by default.

943 changes: 931 additions & 12 deletions packages/api-client/src/schema.d.ts

Large diffs are not rendered by default.

17 changes: 17 additions & 0 deletions packages/api/migrations/0080_usernames.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
ALTER TABLE app.auth_users ADD COLUMN username text;
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM app.auth_users WHERE length(split_part(lower(email),'@',1)) NOT BETWEEN 3 AND 39 OR split_part(lower(email),'@',1) !~ '^[a-z0-9]+(-[a-z0-9]+)*$') THEN
RAISE EXCEPTION 'Username migration: an email prefix is not a valid username; choose a valid username before migrating';
END IF;
IF EXISTS (SELECT 1 FROM app.auth_users GROUP BY split_part(lower(email),'@',1) HAVING count(*)>1) THEN
RAISE EXCEPTION 'Username migration: duplicate email prefixes; choose distinct usernames before migrating';
END IF;
END $$;
UPDATE app.auth_users SET username=split_part(lower(email),'@',1);
ALTER TABLE app.auth_users ALTER COLUMN username SET NOT NULL;
-- Internal identity provisioning still needs an identity before public signup.
ALTER TABLE app.auth_users ALTER COLUMN username SET DEFAULT ('user-' || replace(gen_random_uuid()::text,'-',''));
ALTER TABLE app.auth_users ADD CONSTRAINT auth_users_username_format CHECK(length(username) BETWEEN 3 AND 39 AND username ~ '^[a-z0-9]+(-[a-z0-9]+)*$');
ALTER TABLE app.auth_users ADD CONSTRAINT auth_users_username_unique UNIQUE(username);
INSERT INTO app.schema_migrations(version) VALUES ('0080_usernames') ON CONFLICT DO NOTHING;
27 changes: 27 additions & 0 deletions packages/api/migrations/0081_personal_team_names.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
ALTER TABLE app.tenants ADD COLUMN personal_owner_id uuid REFERENCES app.auth_users(id);
CREATE UNIQUE INDEX tenants_personal_owner ON app.tenants(personal_owner_id) WHERE personal_owner_id IS NOT NULL;
WITH owners AS (SELECT DISTINCT ON (tenant_id) tenant_id,user_id FROM app.members WHERE role='owner' ORDER BY tenant_id,created_at,user_id)
UPDATE app.tenants t SET personal_owner_id=o.user_id,name=u.username FROM owners o JOIN app.auth_users u ON u.id=o.user_id WHERE t.id=o.tenant_id;
CREATE FUNCTION app.personal_team_name() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF NEW.personal_owner_id IS NOT NULL THEN
SELECT username INTO NEW.name FROM app.auth_users WHERE id=NEW.personal_owner_id;
END IF;
RETURN NEW;
END $$;
CREATE TRIGGER personal_team_name BEFORE INSERT OR UPDATE ON app.tenants FOR EACH ROW EXECUTE FUNCTION app.personal_team_name();
CREATE FUNCTION app.assign_personal_team() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF NEW.role='owner' AND NOT EXISTS(SELECT 1 FROM app.tenants WHERE personal_owner_id=NEW.user_id) THEN
UPDATE app.tenants SET personal_owner_id=NEW.user_id WHERE id=NEW.tenant_id AND personal_owner_id IS NULL;
END IF;
RETURN NEW;
END $$;
CREATE TRIGGER assign_personal_team AFTER INSERT ON app.members FOR EACH ROW EXECUTE FUNCTION app.assign_personal_team();
CREATE FUNCTION app.rename_personal_team() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
UPDATE app.tenants SET name=NEW.username,updated_at=now() WHERE personal_owner_id=NEW.id;
RETURN NEW;
END $$;
CREATE TRIGGER rename_personal_team AFTER UPDATE OF username ON app.auth_users FOR EACH ROW EXECUTE FUNCTION app.rename_personal_team();
INSERT INTO app.schema_migrations(version) VALUES ('0081_personal_team_names') ON CONFLICT DO NOTHING;
16 changes: 16 additions & 0 deletions packages/api/migrations/0082_skill_execution_settings.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
ALTER TABLE app.skills ADD COLUMN run_defaults jsonb;
ALTER TABLE app.skills ADD COLUMN encrypted_prompt text;
ALTER TABLE app.skills ADD COLUMN encrypted_script text;
ALTER TABLE app.skills ADD COLUMN settings_revision integer NOT NULL DEFAULT 1;
UPDATE app.skills s SET run_defaults=COALESCE((SELECT run_defaults-'capacity' FROM app.team_settings WHERE tenant_id=s.tenant_id),'{}'::jsonb);
ALTER TABLE app.skills ALTER COLUMN run_defaults SET NOT NULL;
CREATE FUNCTION app.initialize_skill_defaults() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF NEW.run_defaults IS NULL THEN
SELECT COALESCE(run_defaults-'capacity','{}'::jsonb) INTO NEW.run_defaults FROM app.team_settings WHERE tenant_id=NEW.tenant_id;
NEW.run_defaults:=COALESCE(NEW.run_defaults,'{}'::jsonb);
END IF;
RETURN NEW;
END $$;
CREATE TRIGGER initialize_skill_defaults BEFORE INSERT ON app.skills FOR EACH ROW EXECUTE FUNCTION app.initialize_skill_defaults();
INSERT INTO app.schema_migrations(version) VALUES ('0082_skill_execution_settings') ON CONFLICT DO NOTHING;
5 changes: 5 additions & 0 deletions packages/api/migrations/0083_skill_trigger_ownership.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-- Legacy links are converted by the following context-preserving migration.
ALTER TABLE app.trigger_skills ADD COLUMN skill_owned boolean NOT NULL DEFAULT false;
ALTER TABLE app.trigger_skills ALTER COLUMN skill_owned SET DEFAULT true;
CREATE UNIQUE INDEX one_owned_trigger_per_skill ON app.trigger_skills(tenant_id,skill_id) WHERE skill_owned;
INSERT INTO app.schema_migrations(version) VALUES ('0083_skill_trigger_ownership') ON CONFLICT DO NOTHING;
43 changes: 43 additions & 0 deletions packages/api/migrations/0084_migrate_trigger_skills.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
ALTER TABLE app.skills ADD COLUMN legacy_context jsonb NOT NULL DEFAULT '[]'::jsonb;
ALTER TABLE app.skills ADD COLUMN migration_pending boolean NOT NULL DEFAULT false;
DO $$
DECLARE item record; new_id uuid; chosen text; suffix integer; contexts jsonb;
BEGIN
FOR item IN SELECT * FROM app.triggers t ORDER BY tenant_id,id LOOP
new_id:=gen_random_uuid(); suffix:=0;
chosen:=left(item.slug,43)||'-skill-'||left(replace(new_id::text,'-',''),12);
WHILE EXISTS(SELECT 1 FROM app.resource_names WHERE tenant_id=item.tenant_id AND name=chosen) LOOP
suffix:=suffix+1; chosen:=left(item.slug,39)||'-skill-'||left(replace(new_id::text,'-',''),12)||'-'||suffix;
END LOOP;
SELECT COALESCE(jsonb_agg(jsonb_build_object('key',s.key,'encrypted_body',s.encrypted_body,'encrypted_directory',s.encrypted_directory,'artifact_version',s.artifact_version) ORDER BY ts.position),'[]'::jsonb)
INTO contexts FROM (
SELECT skill_id,position FROM app.trigger_skills WHERE tenant_id=item.tenant_id AND trigger_id=item.id
UNION
SELECT skill_id,position FROM app.legacy_trigger_skill_links WHERE tenant_id=item.tenant_id AND trigger_id=item.id AND item.context_review_required
) ts JOIN app.skills s ON s.tenant_id=item.tenant_id AND s.id=ts.skill_id;
INSERT INTO app.skills(tenant_id,id,key,encrypted_body,encrypted_script,run_defaults,legacy_context,migration_pending)
VALUES(item.tenant_id,new_id,chosen,COALESCE(item.encrypted_prompt,''),NULL,
jsonb_strip_nulls(jsonb_build_object(
'executionType',COALESCE(item.execution_config->>'executionType','agent'),
'requiresVm',COALESCE((item.execution_config->>'requiresVm')::boolean,COALESCE(item.execution_config->>'executionType'='code',false) OR COALESCE(item.execution_config->>'connectionId'<>'',false)),
'executionConfigId',NULLIF(item.execution_config->>'connectionId',''),
'vmImage',item.execution_config->>'image','model',item.model,'effort',item.effort,'tags',item.tags,
'modelAccountId',item.execution_config->>'modelAccountId','runScopes',item.run_scopes,
'portableIntegrationIds',COALESCE(item.execution_config->'portableIntegrationIds','[]'::jsonb),
'githubInstallationIds',COALESCE(item.execution_config->'githubInstallationIds','[]'::jsonb),
'linearConnectionId',item.execution_config->>'linearConnectionId','xConnectionIds',COALESCE(item.execution_config->'xConnectionIds','[]'::jsonb),
'concurrencyLimit',item.concurrency_limit,
'allowedTriggerIds',(SELECT COALESCE(jsonb_agg(destination_trigger_id),'[]'::jsonb) FROM app.manual_invocation_permissions WHERE tenant_id=item.tenant_id AND source_trigger_id=item.id)
)),contexts,true);
-- Scripts remain in the original execution projection until a settings save
-- encrypts them into the skill setting. No plaintext script is newly persisted.
INSERT INTO app.configuration_diagnostics(tenant_id,resource_kind,resource_id,code,details)
VALUES(item.tenant_id,'trigger',item.id,'skill_owned_migration',jsonb_build_object('skillId',new_id,'previousName',item.name,'previousPrompt',item.encrypted_prompt,'previousExecutionConfig',item.execution_config));
DELETE FROM app.trigger_skills WHERE tenant_id=item.tenant_id AND trigger_id=item.id;
INSERT INTO app.trigger_skills(tenant_id,trigger_id,skill_id,position,context_skill,skill_owned) VALUES(item.tenant_id,item.id,new_id,0,false,true);
UPDATE app.triggers SET encrypted_prompt='',execution_config=execution_config||jsonb_build_object('skillId',new_id) WHERE tenant_id=item.tenant_id AND id=item.id;
END LOOP;
END $$;
DROP INDEX app.one_owned_trigger_per_skill;
CREATE UNIQUE INDEX one_trigger_per_skill ON app.trigger_skills(tenant_id,skill_id);
INSERT INTO app.schema_migrations(version) VALUES ('0084_migrate_trigger_skills') ON CONFLICT DO NOTHING;
9 changes: 9 additions & 0 deletions packages/api/migrations/0085_skill_content_cache.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
CREATE TABLE app.skill_content_cache (
tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE,
repository text NOT NULL,
commit_sha text NOT NULL,
encrypted_content text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY(tenant_id,repository,commit_sha)
);
INSERT INTO app.schema_migrations(version) VALUES ('0085_skill_content_cache') ON CONFLICT DO NOTHING;
12 changes: 11 additions & 1 deletion packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { skillTriggerInput, skillTriggerResponse } from "./skill-trigger";
import { skillSettings, skillSettingsInput } from "./skill-settings";
import { profileInput, profileResponse } from "./usernames";
import {mediaUploadInput,mediaReceipt,fetchMediaInput} from "./media-contracts";
import {modelProviderConfiguration} from "./pi-provider";
import { teamRunDefaults, teamResponse } from "./flow-schemas";
Expand Down Expand Up @@ -34,7 +37,7 @@ import { traceReplaySchema } from "./trace-replay-schemas";
import { X_OAUTH_SCOPES } from "./x-oauth";
import document from "./api-document.json";
import { authInputs, authSuccess, continuationSuccess, connectionStartInput, connectionStartSuccess, connectionResumeInput, loginSuccess, sessionResponse, type AuthAction } from "./auth-api";
import { skillInput, skillUpdateInput, skillPage, skillResponse, skillTriggersResponse, previewSkillInput, previewPromptResponse } from "./skills";
import { skillDirectoryResponse, skillInput, skillUpdateInput, skillPage, skillResponse, skillTriggersResponse, previewSkillInput, previewPromptResponse } from "./skills";
import { flyConnectionInput, flyConnectionMetadata } from "./fly-account-client";
import { flyExecutionConfiguration, flyExecutionConfigurationInput } from "./fly-execution-configurations";

Expand Down Expand Up @@ -287,6 +290,8 @@ export const API_ROUTES: RouteContract[] = [
}, (service, { params, body }) => service.deleteBearerIntegration(params.integrationId, body), { body: bearerIntegrationDelete, maxBodyBytes: 4096, ownerSession: true }),
authRoute("POST", "/api/v1/auth/connections", "connection-start", "Persist an individual validated MCP connection; sets a per-attempt browser cookie", connectionStartSuccess, connectionStartInput),
authRoute("POST", "/api/v1/auth/connections/resume", "connection-resume", "Resume verified onboarding in the initiating browser; never grants OAuth access", continuationSuccess, connectionResumeInput),
{...authRoute("GET", "/api/v1/profile", "profile", "Read your profile; interactive owner browser session required", profileResponse),ownerSession:true},
{...authRoute("PUT", "/api/v1/profile", "profile-update", "Change your globally unique username; interactive owner browser session required", profileResponse, profileInput),ownerSession:true},
authRoute("GET", "/api/v1/session", "session", "Get current browser session", sessionResponse),
authRoute("POST", "/api/v1/auth/login", "login", "Sign in", loginSuccess, authInputs.login),
authRoute("POST", "/api/v1/auth/signup", "signup", "Request signup; existing accounts return the same accepted response", authSuccess, authInputs.signup, 202),
Expand Down Expand Up @@ -809,6 +814,11 @@ export const API_ROUTES: RouteContract[] = [
route("PUT", "/api/v1/skill-library", "skills:write", { summary: "Select the authoritative skills repository", responses: { "200": { description: "Select the authoritative skills repository", content: { "application/json": { schema: jsonSchema(libraryStatus, "output") } } } } }, (service,{body}) => service.configureSkillLibrary(body), {body:configureLibrary}),
route("POST", "/api/v1/skill-library/token", "skills:write", { summary: "Issue a one-hour repository credential (read-only for GitHub mirrors)", responses: { "200": { description: "Issue a one-hour repository credential (read-only for GitHub mirrors)", content: { "application/json": { schema: jsonSchema(libraryToken, "output") } } } } }, (service) => service.skillLibraryToken()),
route("POST", "/api/v1/skill-library/sync", "skills:write", { summary: "Synchronize the tracked branch", responses: { "200": { description: "Synchronize the tracked branch", content: { "application/json": { schema: jsonSchema(libraryStatus, "output") } } } } }, (service) => service.syncSkillLibrary()),
route("GET", "/api/v1/skills/{skillId}/files", "skills:read", {summary:"Browse the published skill directory at its immutable revision",responses:{"200":{description:"Published files, with base64 encoded contents",content:{"application/json":{schema:jsonSchema(skillDirectoryResponse,"output")}}}}},(service,{params})=>service.getSkillDirectory(params.skillId),{parameters:z.object({skillId:z.uuid()})}),
route("GET", "/api/v1/skills/{skillId}/trigger", ["skills:read","triggers:read"], {summary:"Read a skill's optional trigger",responses:{"200":{description:"Optional trigger",content:{"application/json":{schema:jsonSchema(skillTriggerResponse,"output")}}}}},(service,{params})=>service.getSkillTrigger(params.skillId),{parameters:z.object({skillId:z.uuid()})}),
route("PUT", "/api/v1/skills/{skillId}/trigger", ["skills:write","triggers:write"], {summary:"Configure a skill's event sources and enabled state",responses:{"200":{description:"Saved trigger",content:{"application/json":{schema:jsonSchema(skillTriggerResponse,"output")}}}}},(service,{params,body})=>service.saveSkillTrigger(params.skillId,body),{parameters:z.object({skillId:z.uuid()}),body:skillTriggerInput,maxBodyBytes:1_000_000}),
route("GET", "/api/v1/skills/{skillId}/settings", "skills:read", {summary:"Read skill execution defaults",responses:{"200":{description:"Skill settings",content:{"application/json":{schema:jsonSchema(skillSettings,"output")}}}}},(service,{params})=>service.getSkillSettings(params.skillId),{parameters:z.object({skillId:z.uuid()})}),
route("PUT", "/api/v1/skills/{skillId}/settings", ["skills:write","triggers:write"], {summary:"Save skill execution defaults for future manual and triggered runs",responses:{"200":{description:"Saved skill settings",content:{"application/json":{schema:jsonSchema(skillSettings,"output")}}}}},(service,{params,body})=>service.setSkillSettings(params.skillId,body),{parameters:z.object({skillId:z.uuid()}),body:skillSettingsInput,maxBodyBytes:300_000}),
route("GET", "/api/v1/skills", "skills:read", { summary: "Search global skills", responses: { "200": { description: "Skills", content: { "application/json": { schema: jsonSchema(skillPage, "output") } } } } }, (service, { query }) => service.listSkills(query), { query: skillQuery }),
route("POST", "/api/v1/skills", "skills:write", { summary: "Create a global skill", responses: { "201": { description: "Created", content: { "application/json": { schema: jsonSchema(skillResponse, "output") } } } } }, (service, { body }) => service.createSkill(body), { body: skillInput }),
route("POST", "/api/v1/triggers/preview", "skills:read", { summary: "Preview one skill, a literal prompt and optional Event template", responses: { "200": { description: "Prompt preview", content: { "application/json": { schema: jsonSchema(previewPromptResponse, "output") } } } } }, (service, { body }) => service.previewTriggerPrompt(body), { body: previewSkillInput }),
Expand Down
Loading