@vantageos/agent-engine 0.1.0-alpha.8 → 0.3.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +33 -8
  2. package/dist/component/_generated/api.d.ts +14 -3
  3. package/dist/component/_generated/api.js +0 -25
  4. package/dist/component/_generated/component.d.ts +369 -73
  5. package/dist/component/_generated/component.js +0 -9
  6. package/dist/component/_generated/dataModel.js +0 -9
  7. package/dist/component/_generated/server.js +0 -69
  8. package/dist/component/convex.config.js +0 -44
  9. package/dist/component/engine/agents.d.ts +3 -3
  10. package/dist/component/engine/agents.js +0 -7
  11. package/dist/component/engine/awaitEventTimeout.d.ts +1 -1
  12. package/dist/component/engine/awaitEventTimeout.js +16 -26
  13. package/dist/component/engine/connections.d.ts +74 -0
  14. package/dist/component/engine/connections.js +254 -0
  15. package/dist/component/engine/delegation.d.ts +5 -5
  16. package/dist/component/engine/delegation.js +0 -74
  17. package/dist/component/engine/directory.js +0 -18
  18. package/dist/component/engine/durableJob.d.ts +24 -17
  19. package/dist/component/engine/durableJob.js +182 -138
  20. package/dist/component/engine/mandates.d.ts +2 -2
  21. package/dist/component/engine/mandates.js +0 -59
  22. package/dist/component/engine/queue.d.ts +97 -0
  23. package/dist/component/engine/queue.js +201 -0
  24. package/dist/component/engine/resolvers.d.ts +1 -1
  25. package/dist/component/engine/resolvers.js +6 -18
  26. package/dist/component/engine/sandboxCallback.d.ts +2 -2
  27. package/dist/component/engine/sandboxCallback.js +2 -79
  28. package/dist/component/engine/sandboxConfigProvider.d.ts +9 -0
  29. package/dist/component/engine/sandboxConfigProvider.js +32 -0
  30. package/dist/component/engine/sessions.d.ts +28 -10
  31. package/dist/component/engine/sessions.js +130 -170
  32. package/dist/component/engine/streams.d.ts +47 -0
  33. package/dist/component/engine/streams.js +162 -0
  34. package/dist/component/engine/toolApprovals.d.ts +1 -1
  35. package/dist/component/engine/toolApprovals.js +12 -37
  36. package/dist/component/engine/vpConnection.js +0 -40
  37. package/dist/component/engine/wakeup.d.ts +7 -9
  38. package/dist/component/engine/wakeup.js +54 -127
  39. package/dist/component/engine/workflows.d.ts +26 -8
  40. package/dist/component/engine/workflows.js +59 -64
  41. package/dist/component/engine/world.d.ts +250 -0
  42. package/dist/component/engine/world.js +689 -0
  43. package/dist/component/lib/auth.js +0 -26
  44. package/dist/component/lib/connectionSecret.d.ts +5 -0
  45. package/dist/component/lib/connectionSecret.js +32 -0
  46. package/dist/component/schema.d.ts +240 -175
  47. package/dist/component/schema.js +134 -294
  48. package/package.json +21 -6
  49. package/dist/component/engine/habits.d.ts +0 -70
  50. package/dist/component/engine/habits.js +0 -218
  51. package/dist/component/testFixtures/callerSteps.d.ts +0 -20
  52. package/dist/component/testFixtures/callerSteps.js +0 -90
  53. package/dist/component/testFixtures/delegationDemoWorkflow.d.ts +0 -18
  54. package/dist/component/testFixtures/delegationDemoWorkflow.js +0 -75
  55. package/dist/component/testFixtures/sandboxDemoWorkflow.d.ts +0 -19
  56. package/dist/component/testFixtures/sandboxDemoWorkflow.js +0 -69
  57. package/dist/component/testFixtures/vpTool.d.ts +0 -4
  58. package/dist/component/testFixtures/vpTool.js +0 -25
  59. package/dist/component/testFixtures/wakeupDemoWorkflow.d.ts +0 -19
  60. package/dist/component/testFixtures/wakeupDemoWorkflow.js +0 -77
  61. package/dist/component/testFixtures/wakeupWork.d.ts +0 -8
  62. package/dist/component/testFixtures/wakeupWork.js +0 -21
@@ -1,10 +1 @@
1
- /* eslint-disable */
2
- /**
3
- * Generated data model types.
4
- *
5
- * THIS CODE IS AUTOMATICALLY GENERATED.
6
- *
7
- * To regenerate, run `npx convex dev`.
8
- * @module
9
- */
10
1
  export {};
@@ -1,77 +1,8 @@
1
- /* eslint-disable */
2
- /**
3
- * Generated utilities for implementing server-side Convex query and mutation functions.
4
- *
5
- * THIS CODE IS AUTOMATICALLY GENERATED.
6
- *
7
- * To regenerate, run `npx convex dev`.
8
- * @module
9
- */
10
1
  import { actionGeneric, httpActionGeneric, queryGeneric, mutationGeneric, internalActionGeneric, internalMutationGeneric, internalQueryGeneric, } from "convex/server";
11
- /**
12
- * Define a query in this Convex app's public API.
13
- *
14
- * This function will be allowed to read your Convex database and will be accessible from the client.
15
- *
16
- * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
17
- * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
18
- */
19
2
  export const query = queryGeneric;
20
- /**
21
- * Define a query that is only accessible from other Convex functions (but not from the client).
22
- *
23
- * This function will be allowed to read from your Convex database. It will not be accessible from the client.
24
- *
25
- * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
26
- * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
27
- */
28
3
  export const internalQuery = internalQueryGeneric;
29
- /**
30
- * Define a mutation in this Convex app's public API.
31
- *
32
- * This function will be allowed to modify your Convex database and will be accessible from the client.
33
- *
34
- * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
35
- * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
36
- */
37
4
  export const mutation = mutationGeneric;
38
- /**
39
- * Define a mutation that is only accessible from other Convex functions (but not from the client).
40
- *
41
- * This function will be allowed to modify your Convex database. It will not be accessible from the client.
42
- *
43
- * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
44
- * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
45
- */
46
5
  export const internalMutation = internalMutationGeneric;
47
- /**
48
- * Define an action in this Convex app's public API.
49
- *
50
- * An action is a function which can execute any JavaScript code, including non-deterministic
51
- * code and code with side-effects, like calling third-party services.
52
- * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
53
- * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
54
- *
55
- * @param func - The action. It receives an {@link ActionCtx} as its first argument.
56
- * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
57
- */
58
6
  export const action = actionGeneric;
59
- /**
60
- * Define an action that is only accessible from other Convex functions (but not from the client).
61
- *
62
- * @param func - The function. It receives an {@link ActionCtx} as its first argument.
63
- * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
64
- */
65
7
  export const internalAction = internalActionGeneric;
66
- /**
67
- * Define an HTTP action.
68
- *
69
- * The wrapped function will be used to respond to HTTP requests received
70
- * by a Convex deployment if the requests matches the path and method where
71
- * this action is routed. Be sure to route your httpAction in `convex/http.js`.
72
- *
73
- * @param func - The function. It receives an {@link ActionCtx} as its first argument
74
- * and a Fetch API `Request` object as its second.
75
- * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
76
- */
77
8
  export const httpAction = httpActionGeneric;
@@ -4,49 +4,6 @@ import workpool from "@convex-dev/workpool/convex.config";
4
4
  import agent from "@convex-dev/agent/convex.config";
5
5
  import rateLimiter from "@convex-dev/rate-limiter/convex.config";
6
6
  import shardedCounter from "@convex-dev/sharded-counter/convex.config";
7
- import crons from "@convex-dev/crons/convex.config";
8
- // @vantageos/agent-engine — Convex COMPONENT definition (pattern
9
- // `@convex-dev/*`, verified against the published shape of
10
- // `@convex-dev/workflow` — `defineComponent(name)` + a `convex.config.ts`
11
- // at the root of the *package that gets published*, not merely at the
12
- // root of the git repo).
13
- //
14
- // This is what a consumer registers via:
15
- // import agentEngine from "@vantageos/agent-engine/convex.config";
16
- // app.use(agentEngine);
17
- //
18
- // This file declares agent-engine's COMPONENT IDENTITY and its
19
- // sub-component composition (workflow + 2 named workpools + agent), which
20
- // is what makes the `@vantageos/agent-engine/convex.config` import
21
- // RESOLVE for a consumer and what makes `app.use(agentEngine)` build
22
- // without throwing.
23
- //
24
- // T2-QUATER (this pass): `convex/component/engine/durableJob.ts` +
25
- // `convex/component/schema.ts` (its `durableJobs` table) +
26
- // `convex/component/lib/auth.ts` (orgId isolation) are now CO-LOCATED in
27
- // this same directory tree, alongside this file — this is what a
28
- // consumer's `npx convex dev`/`deploy` actually bundles and deploys under
29
- // the component boundary, and what makes
30
- // `components.agentEngine.engine.durableJob.start(...)` resolve to a real
31
- // function instead of `undefined`. See README.md "What's callable" for
32
- // the exact, current boundary: durableJob is IN; the rest of the agent
33
- // aggregate (agents, skills, subagents, connections, habits,
34
- // sandboxConfig, toolApprovals, modelKeys, sessions, sessionEvents,
35
- // awaitEventTimeouts, wakeableWork) is deliberately NOT yet re-hosted
36
- // here — porting those without a working component-level test harness
37
- // behind each of them would violate Day 128 (never ship unverified).
38
- // Mandates (bounded, weighted spending authority per agent/org/scope) are
39
- // hosted under this component boundary, using official `@convex-dev/*`
40
- // libraries only -- no canary/alpha dependency for a guardrail:
41
- // `rate-limiter` for the fails-closed spend gate itself, `sharded-counter`
42
- // for the usage rollup. See component/engine/mandates.ts.
43
- // Habits (a dynamic, per-agent/org cron schedule editable at runtime) are
44
- // also hosted under this component boundary, ported byte-identical from the
45
- // repo-root prototype (convex/habits.ts). `crons` is a sub-component of
46
- // THIS component -- create/updateSchedule/enable/disable register or tear
47
- // down a runtime cron job via `@convex-dev/crons` inside the SAME Convex
48
- // mutation transaction that writes the `habits` row, so no habit schedule
49
- // change ever requires a redeploy. See component/engine/habits.ts.
50
7
  const component = defineComponent("agentEngine");
51
8
  component.use(workflow);
52
9
  component.use(workpool, { name: "agentTurnPool" });
@@ -54,5 +11,4 @@ component.use(workpool, { name: "wakeupPool" });
54
11
  component.use(agent);
55
12
  component.use(rateLimiter);
56
13
  component.use(shardedCounter);
57
- component.use(crons);
58
14
  export default component;
@@ -23,10 +23,10 @@ export declare const get: import("convex/server").RegisteredQuery<"public", {
23
23
  maxInputTokensPerSession?: number | false | undefined;
24
24
  name: string;
25
25
  orgId: string;
26
- status: "draft" | "live" | "archived";
27
- createdAt: number;
28
- updatedAt: number;
29
26
  instructions: string;
30
27
  model: string;
28
+ status: "draft" | "live" | "archived";
31
29
  createdBy: string;
30
+ createdAt: number;
31
+ updatedAt: number;
32
32
  } | null>>;
@@ -1,13 +1,6 @@
1
1
  import { v } from "convex/values";
2
2
  import { mutation, query } from "../_generated/server.js";
3
3
  import { requireOrgId } from "../lib/auth.js";
4
- // engine/agents — MINIMAL root-sheet bootstrap for the sessions surface
5
- // (T2-QUINQUIES). `sessions.start` needs an `agentId` it can read INSIDE
6
- // the component boundary (component isolation: it cannot reach into a
7
- // consumer app's own `agents` table). This is deliberately narrow: only
8
- // `create`/`get`, no `update`/`list`/skills/connections — the full agent
9
- // aggregate CRUD stays out of this component boundary for this pass (see
10
- // component/schema.ts SCOPE note).
11
4
  const reasoningEffort = v.union(v.literal("none"), v.literal("low"), v.literal("medium"), v.literal("high"));
12
5
  const modelProvider = v.union(v.literal("gateway"), v.literal("openrouter"));
13
6
  const maxInputTokensPerSession = v.union(v.number(), v.literal(false));
@@ -1,6 +1,6 @@
1
1
  export declare const schedule: import("convex/server").RegisteredMutation<"public", {
2
2
  orgId: string;
3
- sessionId: import("convex/values").GenericId<"sessions">;
3
+ sessionId: string;
4
4
  awaitedEventName: string;
5
5
  timeoutMs: number;
6
6
  }, Promise<import("convex/values").GenericId<"awaitEventTimeouts">>>;
@@ -2,41 +2,25 @@ import { v } from "convex/values";
2
2
  import { internal } from "../_generated/api.js";
3
3
  import { internalMutation, mutation } from "../_generated/server.js";
4
4
  import { assertSameOrg, requireOrgId } from "../lib/auth.js";
5
- // engine/awaitEventTimeout — self-built timeout for step.awaitEvent
6
- // (workflow#177: "Convex does not provide a native timeout for
7
- // awaitEvent"). We schedule a mutation that
8
- // fires a "blank" `sandbox.timeout` sessionEvent at the deadline; the
9
- // workflow's `awaitEvent` call is written to also accept this event name so
10
- // it wakes up even if the awaited event never arrives. Pattern:
11
- // maintainer's posted code in workflow#177, adapted to our sessionEvents
12
- // table.
13
- //
14
- // NOTE ("intentional divergence from Eve"): orgId is an EXPLICIT ARGUMENT on
15
- // every public function, never derived from `ctx.auth` -- auth does NOT
16
- // propagate across a component boundary (component/lib/auth.ts). Also:
17
- // `sessionEvents.name`'s union in component/schema.ts did not previously
18
- // include `sandbox.timeout` -- it has been added there (and mirrored in
19
- // `engine/sessions.listEvents`'s return validator) as part of this
20
- // migration, otherwise `fire`'s insert below would not compile under the
21
- // strict build.
5
+ import { insertEvent, loadSessionRun } from "./sessions.js";
6
+ import { findRunIdByCorrelation, legacyCorrelationId, loadRun, } from "./world.js";
22
7
  export const schedule = mutation({
23
8
  args: {
24
9
  orgId: v.string(),
25
- sessionId: v.id("sessions"),
10
+ sessionId: v.string(),
26
11
  awaitedEventName: v.string(),
27
12
  timeoutMs: v.number(),
28
13
  },
29
14
  returns: v.id("awaitEventTimeouts"),
30
15
  handler: async (ctx, args) => {
31
16
  const orgId = requireOrgId(args.orgId);
32
- const session = await ctx.db.get(args.sessionId);
33
- assertSameOrg(orgId, session, "Session not found");
17
+ const run = await loadSessionRun(ctx, orgId, args.sessionId);
34
18
  if (args.timeoutMs <= 0) {
35
19
  throw new Error("Validation: timeoutMs must be > 0");
36
20
  }
37
21
  const timeoutRowId = await ctx.db.insert("awaitEventTimeouts", {
38
22
  orgId,
39
- sessionId: args.sessionId,
23
+ runId: run.runId,
40
24
  awaitedEventName: args.awaitedEventName,
41
25
  deadlineAt: Date.now() + args.timeoutMs,
42
26
  });
@@ -59,22 +43,28 @@ export const cancel = mutation({
59
43
  return null;
60
44
  },
61
45
  });
62
- // internal — invoked only by the scheduler, never by a client.
63
46
  export const fire = internalMutation({
64
47
  args: { timeoutRowId: v.id("awaitEventTimeouts") },
65
48
  returns: v.null(),
66
49
  handler: async (ctx, args) => {
67
50
  const row = await ctx.db.get(args.timeoutRowId);
68
51
  if (!row || row.firedAt || row.cancelledAt) {
69
- return null; // already resolved by the real event or by a prior fire
52
+ return null;
70
53
  }
71
54
  await ctx.db.patch(args.timeoutRowId, { firedAt: Date.now() });
72
- await ctx.db.insert("sessionEvents", {
55
+ let runId = row.runId;
56
+ if (runId === undefined && row.sessionId !== undefined) {
57
+ runId =
58
+ (await findRunIdByCorrelation(ctx, row.orgId, legacyCorrelationId("session", row.sessionId))) ?? undefined;
59
+ }
60
+ if (runId === undefined)
61
+ return null;
62
+ const run = await loadRun(ctx, row.orgId, runId, "session", "Session not found");
63
+ await insertEvent(ctx, {
73
64
  orgId: row.orgId,
74
- sessionId: row.sessionId,
65
+ run,
75
66
  name: "sandbox.timeout",
76
67
  payload: JSON.stringify({ awaitedEventName: row.awaitedEventName }),
77
- createdAt: Date.now(),
78
68
  });
79
69
  return null;
80
70
  },
@@ -0,0 +1,74 @@
1
+ import type { Id } from "../_generated/dataModel.js";
2
+ export declare const create: import("convex/server").RegisteredMutation<"public", {
3
+ secretPlaintext?: string | undefined;
4
+ encryptionKeyBase64?: string | undefined;
5
+ name: string;
6
+ orgId: string;
7
+ type: "mcp" | "openapi";
8
+ agentId: import("convex/values").GenericId<"agents">;
9
+ serverConfig: string;
10
+ authMode: "none" | "app-token" | "user-oauth" | "header";
11
+ }, Promise<Id<"connections">>>;
12
+ export declare const get: import("convex/server").RegisteredQuery<"public", {
13
+ orgId: string;
14
+ connectionId: import("convex/values").GenericId<"connections">;
15
+ }, Promise<{
16
+ _id: Id<"connections">;
17
+ _creationTime: number;
18
+ orgId: string;
19
+ agentId: Id<"agents">;
20
+ type: "mcp" | "openapi";
21
+ name: string;
22
+ serverConfig: string;
23
+ authMode: "none" | "app-token" | "user-oauth" | "header";
24
+ principalType: "app" | "user";
25
+ status: "active" | "pending_authorization" | "error";
26
+ hasSecret: boolean;
27
+ createdAt: number;
28
+ updatedAt: number;
29
+ }>>;
30
+ export declare const listByAgent: import("convex/server").RegisteredQuery<"public", {
31
+ orgId: string;
32
+ agentId: import("convex/values").GenericId<"agents">;
33
+ }, Promise<{
34
+ _id: Id<"connections">;
35
+ _creationTime: number;
36
+ orgId: string;
37
+ agentId: Id<"agents">;
38
+ type: "mcp" | "openapi";
39
+ name: string;
40
+ serverConfig: string;
41
+ authMode: "none" | "app-token" | "user-oauth" | "header";
42
+ principalType: "app" | "user";
43
+ status: "active" | "pending_authorization" | "error";
44
+ hasSecret: boolean;
45
+ createdAt: number;
46
+ updatedAt: number;
47
+ }[]>>;
48
+ export declare const requestAuthorization: import("convex/server").RegisteredMutation<"public", {
49
+ orgId: string;
50
+ awaitedEventName: string;
51
+ workflowId: string;
52
+ connectionId: import("convex/values").GenericId<"connections">;
53
+ url: string;
54
+ userCode: string;
55
+ }, Promise<Id<"connectionAuthorizations">>>;
56
+ export declare const getAuthorizationStatus: import("convex/server").RegisteredQuery<"public", {
57
+ orgId: string;
58
+ connectionAuthorizationId: import("convex/values").GenericId<"connectionAuthorizations">;
59
+ }, Promise<{
60
+ status: "pending" | "denied" | "authorized";
61
+ url: string;
62
+ userCode: string;
63
+ resultSummary: string | undefined;
64
+ }>>;
65
+ export declare const completeAuthorization: import("convex/server").RegisteredMutation<"public", {
66
+ resultSummary?: string | undefined;
67
+ secretPlaintext?: string | undefined;
68
+ encryptionKeyBase64?: string | undefined;
69
+ orgId: string;
70
+ outcome: "denied" | "authorized";
71
+ connectionAuthorizationId: import("convex/values").GenericId<"connectionAuthorizations">;
72
+ }, Promise<{
73
+ outcome: "woke" | "already-resolved";
74
+ }>>;
@@ -0,0 +1,254 @@
1
+ import { WorkflowManager } from "@convex-dev/workflow";
2
+ import { v } from "convex/values";
3
+ import { components } from "../_generated/api.js";
4
+ import { mutation, query } from "../_generated/server.js";
5
+ import { assertSameOrg, requireOrgId } from "../lib/auth.js";
6
+ import { encryptSecret } from "../lib/connectionSecret.js";
7
+ const workflow = new WorkflowManager(components.workflow);
8
+ const authModeValidator = v.union(v.literal("app-token"), v.literal("user-oauth"), v.literal("none"), v.literal("header"));
9
+ function principalTypeForAuthMode(authMode) {
10
+ return authMode === "user-oauth" ? "user" : "app";
11
+ }
12
+ const connectionTypeValidator = v.union(v.literal("mcp"), v.literal("openapi"));
13
+ const connectionStatusValidator = v.union(v.literal("active"), v.literal("pending_authorization"), v.literal("error"));
14
+ const connectionPublicDoc = v.object({
15
+ _id: v.id("connections"),
16
+ _creationTime: v.number(),
17
+ orgId: v.string(),
18
+ agentId: v.id("agents"),
19
+ type: connectionTypeValidator,
20
+ name: v.string(),
21
+ serverConfig: v.string(),
22
+ authMode: authModeValidator,
23
+ principalType: v.union(v.literal("app"), v.literal("user")),
24
+ status: connectionStatusValidator,
25
+ hasSecret: v.boolean(),
26
+ createdAt: v.number(),
27
+ updatedAt: v.number(),
28
+ });
29
+ function toPublicDoc(row) {
30
+ return {
31
+ _id: row._id,
32
+ _creationTime: row._creationTime,
33
+ orgId: row.orgId,
34
+ agentId: row.agentId,
35
+ type: row.type,
36
+ name: row.name,
37
+ serverConfig: row.serverConfig,
38
+ authMode: row.authMode,
39
+ principalType: principalTypeForAuthMode(row.authMode),
40
+ status: row.status,
41
+ hasSecret: row.encryptedSecretCiphertext !== undefined,
42
+ createdAt: row.createdAt,
43
+ updatedAt: row.updatedAt,
44
+ };
45
+ }
46
+ export const create = mutation({
47
+ args: {
48
+ orgId: v.string(),
49
+ agentId: v.id("agents"),
50
+ type: connectionTypeValidator,
51
+ name: v.string(),
52
+ serverConfig: v.string(),
53
+ authMode: authModeValidator,
54
+ secretPlaintext: v.optional(v.string()),
55
+ encryptionKeyBase64: v.optional(v.string()),
56
+ },
57
+ returns: v.id("connections"),
58
+ handler: async (ctx, args) => {
59
+ const orgId = requireOrgId(args.orgId);
60
+ const agent = await ctx.db.get(args.agentId);
61
+ assertSameOrg(orgId, agent, "Agent not found");
62
+ if (args.name.trim().length === 0) {
63
+ throw new Error("Validation: name must not be empty");
64
+ }
65
+ let encryptedSecretCiphertext;
66
+ let encryptedSecretIv;
67
+ if (args.authMode === "app-token" || args.authMode === "header") {
68
+ if (!args.secretPlaintext) {
69
+ throw new Error(`MUST_REFUSE: connection authMode "${args.authMode}" requires secretPlaintext, none was supplied`);
70
+ }
71
+ if (!args.encryptionKeyBase64) {
72
+ throw new Error(`MUST_REFUSE: connection authMode "${args.authMode}" requires encryptionKeyBase64, none was supplied`);
73
+ }
74
+ const encrypted = await encryptSecret(args.secretPlaintext, args.encryptionKeyBase64);
75
+ encryptedSecretCiphertext = encrypted.ciphertextBase64;
76
+ encryptedSecretIv = encrypted.ivBase64;
77
+ }
78
+ else if (args.authMode === "none") {
79
+ if (args.secretPlaintext) {
80
+ throw new Error('MUST_REFUSE: connection authMode "none" must not carry a secretPlaintext');
81
+ }
82
+ }
83
+ const now = Date.now();
84
+ return await ctx.db.insert("connections", {
85
+ orgId,
86
+ agentId: args.agentId,
87
+ type: args.type,
88
+ name: args.name,
89
+ serverConfig: args.serverConfig,
90
+ authMode: args.authMode,
91
+ encryptedSecretCiphertext,
92
+ encryptedSecretIv,
93
+ status: "active",
94
+ createdAt: now,
95
+ updatedAt: now,
96
+ });
97
+ },
98
+ });
99
+ export const get = query({
100
+ args: { orgId: v.string(), connectionId: v.id("connections") },
101
+ returns: connectionPublicDoc,
102
+ handler: async (ctx, args) => {
103
+ const orgId = requireOrgId(args.orgId);
104
+ const row = await ctx.db.get(args.connectionId);
105
+ assertSameOrg(orgId, row, "Connection not found");
106
+ return toPublicDoc(row);
107
+ },
108
+ });
109
+ export const listByAgent = query({
110
+ args: { orgId: v.string(), agentId: v.id("agents") },
111
+ returns: v.array(connectionPublicDoc),
112
+ handler: async (ctx, args) => {
113
+ const orgId = requireOrgId(args.orgId);
114
+ const agent = await ctx.db.get(args.agentId);
115
+ assertSameOrg(orgId, agent, "Agent not found");
116
+ const rows = await ctx.db
117
+ .query("connections")
118
+ .withIndex("by_org_agent", (q) => q.eq("orgId", orgId).eq("agentId", args.agentId))
119
+ .collect();
120
+ return rows.map((row) => toPublicDoc(row));
121
+ },
122
+ });
123
+ export const requestAuthorization = mutation({
124
+ args: {
125
+ orgId: v.string(),
126
+ connectionId: v.id("connections"),
127
+ workflowId: v.string(),
128
+ awaitedEventName: v.string(),
129
+ url: v.string(),
130
+ userCode: v.string(),
131
+ },
132
+ returns: v.id("connectionAuthorizations"),
133
+ handler: async (ctx, args) => {
134
+ const orgId = requireOrgId(args.orgId);
135
+ const connection = await ctx.db.get(args.connectionId);
136
+ assertSameOrg(orgId, connection, "Connection not found");
137
+ if (connection.authMode !== "user-oauth") {
138
+ throw new Error(`MUST_REFUSE: requestAuthorization requires authMode "user-oauth", connection has "${connection.authMode}"`);
139
+ }
140
+ if (args.workflowId.length === 0) {
141
+ throw new Error("MUST_REFUSE: workflowId must not be empty");
142
+ }
143
+ if (args.awaitedEventName.length === 0) {
144
+ throw new Error("MUST_REFUSE: awaitedEventName must not be empty");
145
+ }
146
+ if (args.url.trim().length === 0) {
147
+ throw new Error("MUST_REFUSE: authorization.required challenge requires a non-empty url, none was supplied");
148
+ }
149
+ if (args.userCode.trim().length === 0) {
150
+ throw new Error("MUST_REFUSE: authorization.required challenge requires a non-empty userCode, none was supplied");
151
+ }
152
+ const now = Date.now();
153
+ const authorizationId = await ctx.db.insert("connectionAuthorizations", {
154
+ orgId,
155
+ connectionId: args.connectionId,
156
+ workflowId: args.workflowId,
157
+ awaitedEventName: args.awaitedEventName,
158
+ url: args.url,
159
+ userCode: args.userCode,
160
+ status: "pending",
161
+ createdAt: now,
162
+ updatedAt: now,
163
+ });
164
+ await ctx.db.patch(args.connectionId, {
165
+ status: "pending_authorization",
166
+ updatedAt: now,
167
+ });
168
+ return authorizationId;
169
+ },
170
+ });
171
+ export const getAuthorizationStatus = query({
172
+ args: { orgId: v.string(), connectionAuthorizationId: v.id("connectionAuthorizations") },
173
+ returns: v.object({
174
+ status: v.union(v.literal("pending"), v.literal("authorized"), v.literal("denied")),
175
+ url: v.string(),
176
+ userCode: v.string(),
177
+ resultSummary: v.optional(v.string()),
178
+ }),
179
+ handler: async (ctx, args) => {
180
+ const orgId = requireOrgId(args.orgId);
181
+ const row = await ctx.db.get(args.connectionAuthorizationId);
182
+ assertSameOrg(orgId, row, "Connection authorization not found");
183
+ return {
184
+ status: row.status,
185
+ url: row.url,
186
+ userCode: row.userCode,
187
+ resultSummary: row.resultSummary,
188
+ };
189
+ },
190
+ });
191
+ export const completeAuthorization = mutation({
192
+ args: {
193
+ orgId: v.string(),
194
+ connectionAuthorizationId: v.id("connectionAuthorizations"),
195
+ outcome: v.union(v.literal("authorized"), v.literal("denied")),
196
+ secretPlaintext: v.optional(v.string()),
197
+ encryptionKeyBase64: v.optional(v.string()),
198
+ resultSummary: v.optional(v.string()),
199
+ },
200
+ returns: v.object({
201
+ outcome: v.union(v.literal("woke"), v.literal("already-resolved")),
202
+ }),
203
+ handler: async (ctx, args) => {
204
+ const orgId = requireOrgId(args.orgId);
205
+ const authorization = await ctx.db.get(args.connectionAuthorizationId);
206
+ assertSameOrg(orgId, authorization, "Connection authorization not found");
207
+ if (authorization.status !== "pending") {
208
+ return { outcome: "already-resolved" };
209
+ }
210
+ const connection = await ctx.db.get(authorization.connectionId);
211
+ assertSameOrg(orgId, connection, "Connection not found");
212
+ let encryptedSecretCiphertext = connection.encryptedSecretCiphertext;
213
+ let encryptedSecretIv = connection.encryptedSecretIv;
214
+ let connectionStatus = "error";
215
+ if (args.outcome === "authorized") {
216
+ if (!args.secretPlaintext) {
217
+ throw new Error('MUST_REFUSE: completeAuthorization outcome "authorized" requires secretPlaintext, none was supplied');
218
+ }
219
+ if (!args.encryptionKeyBase64) {
220
+ throw new Error('MUST_REFUSE: completeAuthorization outcome "authorized" requires encryptionKeyBase64, none was supplied');
221
+ }
222
+ const encrypted = await encryptSecret(args.secretPlaintext, args.encryptionKeyBase64);
223
+ encryptedSecretCiphertext = encrypted.ciphertextBase64;
224
+ encryptedSecretIv = encrypted.ivBase64;
225
+ connectionStatus = "active";
226
+ }
227
+ const now = Date.now();
228
+ await ctx.db.patch(authorization._id, {
229
+ status: args.outcome,
230
+ resultSummary: args.resultSummary,
231
+ updatedAt: now,
232
+ resolvedAt: now,
233
+ });
234
+ await ctx.db.patch(connection._id, {
235
+ encryptedSecretCiphertext,
236
+ encryptedSecretIv,
237
+ status: connectionStatus,
238
+ updatedAt: now,
239
+ });
240
+ await workflow.sendEvent(ctx, {
241
+ workflowId: authorization.workflowId,
242
+ name: authorization.awaitedEventName,
243
+ validator: v.object({
244
+ status: v.union(v.literal("completed"), v.literal("failed")),
245
+ resultSummary: v.optional(v.string()),
246
+ }),
247
+ value: {
248
+ status: args.outcome === "authorized" ? "completed" : "failed",
249
+ resultSummary: args.resultSummary,
250
+ },
251
+ });
252
+ return { outcome: "woke" };
253
+ },
254
+ });
@@ -17,17 +17,17 @@ export declare const listSubagents: import("convex/server").RegisteredQuery<"pub
17
17
  orgId: string;
18
18
  createdAt: number;
19
19
  toolName: string;
20
- enabled: boolean;
21
20
  parentAgentId: import("convex/values").GenericId<"agents">;
22
21
  childAgentId: import("convex/values").GenericId<"agents">;
22
+ enabled: boolean;
23
23
  }[]>>;
24
24
  export declare const delegateToSubagent: import("convex/server").RegisteredAction<"public", {
25
25
  payload?: string | undefined;
26
26
  orgId: string;
27
- workflowId: string;
28
27
  awaitedEventName: string;
29
28
  scope: string;
30
29
  reason: string;
30
+ workflowId: string;
31
31
  cost: number;
32
32
  subagentId: import("convex/values").GenericId<"subagents">;
33
33
  workFunctionHandle: string;
@@ -35,11 +35,11 @@ export declare const delegateToSubagent: import("convex/server").RegisteredActio
35
35
  export declare const invokeAgentClone: import("convex/server").RegisteredAction<"public", {
36
36
  payload?: string | undefined;
37
37
  orgId: string;
38
- workflowId: string;
39
38
  agentId: import("convex/values").GenericId<"agents">;
40
39
  awaitedEventName: string;
41
40
  scope: string;
42
41
  reason: string;
42
+ workflowId: string;
43
43
  cost: number;
44
44
  workFunctionHandle: string;
45
45
  viaAgentTool: boolean;
@@ -61,15 +61,15 @@ export declare const getAgentInternal: import("convex/server").RegisteredQuery<"
61
61
  } | null>>;
62
62
  export declare const recordDelegationStartInternal: import("convex/server").RegisteredMutation<"internal", {
63
63
  orgId: string;
64
- workflowId: string;
65
64
  toolName: string;
66
65
  awaitedEventName: string;
66
+ workflowId: string;
67
67
  parentAgentId: import("convex/values").GenericId<"agents">;
68
68
  childAgentId: import("convex/values").GenericId<"agents">;
69
69
  }, Promise<import("convex/values").GenericId<"delegationRuns">>>;
70
70
  export declare const recordCloneStartInternal: import("convex/server").RegisteredMutation<"internal", {
71
71
  orgId: string;
72
- workflowId: string;
73
72
  agentId: import("convex/values").GenericId<"agents">;
74
73
  awaitedEventName: string;
74
+ workflowId: string;
75
75
  }, Promise<import("convex/values").GenericId<"agentCloneRuns">>>;