@lunora/agent 1.0.0-alpha.2 → 1.0.0-alpha.200

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 (95) hide show
  1. package/dist/channels.d.mts +52 -33
  2. package/dist/channels.d.ts +52 -33
  3. package/dist/channels.mjs +1 -181
  4. package/dist/component.d.mts +97 -70
  5. package/dist/component.d.ts +97 -70
  6. package/dist/component.mjs +2 -407
  7. package/dist/inbound.d.mts +24 -22
  8. package/dist/inbound.d.ts +24 -22
  9. package/dist/inbound.mjs +1 -32
  10. package/dist/index.d.mts +576 -497
  11. package/dist/index.d.ts +576 -497
  12. package/dist/index.mjs +1 -18
  13. package/dist/naming.d.mts +18 -22
  14. package/dist/naming.d.ts +18 -22
  15. package/dist/naming.mjs +1 -8
  16. package/dist/packem_shared/AGENT_MODULE-M4D1EejI.mjs +1 -0
  17. package/dist/packem_shared/DEFAULT_DISPATCH_TIMEOUT_MS-wjR1QXHX-BHqkRjkN.mjs +1 -0
  18. package/dist/packem_shared/VoiceSessionDO-CB_yuzWV.mjs +1 -0
  19. package/dist/packem_shared/adaptMcpResult-CVlq-_TO.mjs +2 -0
  20. package/dist/packem_shared/agent-ai-CxEYOyOu.mjs +1 -0
  21. package/dist/packem_shared/agent-loop-DyJWnyiT.mjs +3 -0
  22. package/dist/packem_shared/agentAsTool-1Gwq45M3.mjs +1 -0
  23. package/dist/packem_shared/braintrustTelemetry-Byne8uPK.mjs +1 -0
  24. package/dist/packem_shared/branch-marker-boZ00zmk.mjs +1 -0
  25. package/dist/packem_shared/buildModelMessages-Y4tGo1T9.mjs +5 -0
  26. package/dist/packem_shared/codeTool-BQb-K3my.mjs +1 -0
  27. package/dist/packem_shared/collectAgenticMemoryTools-BeMWT2qt.mjs +1 -0
  28. package/dist/packem_shared/combineTelemetry-DgE9W9G8.mjs +1 -0
  29. package/dist/packem_shared/common-CJSjtsfv.mjs +1 -0
  30. package/dist/packem_shared/compileAgentWorkflow-C287O2ux.mjs +1 -0
  31. package/dist/packem_shared/component-shared-G8ngerkU.mjs +1 -0
  32. package/dist/packem_shared/consoleTelemetry-BZY3Y-Ly.mjs +1 -0
  33. package/dist/packem_shared/createAgentContext-BxDMNWNG.mjs +1 -0
  34. package/dist/packem_shared/createAgentGenerate-EEFNvpS5.mjs +3 -0
  35. package/dist/packem_shared/defineAgent-CjxGfOg7.mjs +3 -0
  36. package/dist/packem_shared/defineSkill-DGGvDWNq.mjs +1 -0
  37. package/dist/packem_shared/fnv1a-BNN96GYb.mjs +1 -0
  38. package/dist/packem_shared/functionTool-D3CP4f8-.mjs +1 -0
  39. package/dist/packem_shared/in-flight-calls-GH1A_1P3.mjs +1 -0
  40. package/dist/packem_shared/jsCodeTool-BLOvjXGF.mjs +18 -0
  41. package/dist/packem_shared/normalizeEntityName-k3fjicAG.mjs +2 -0
  42. package/dist/packem_shared/otlpTelemetry-ByqrB-72.mjs +1 -0
  43. package/dist/packem_shared/positive-integer-ztHqqpBk.mjs +1 -0
  44. package/dist/packem_shared/runAgentLoop-BIjYgCLE.mjs +1 -0
  45. package/dist/packem_shared/runVoiceTurn-CtKjHnfU.mjs +1 -0
  46. package/dist/packem_shared/sandbox-budgets-DDvj4Orr.mjs +1 -0
  47. package/dist/packem_shared/sandboxComponent-Du0yENEO.mjs +7 -0
  48. package/dist/packem_shared/sentryTelemetry-BHeydiAB.mjs +1 -0
  49. package/dist/packem_shared/tool-output-Cmk3JWMG.mjs +1 -0
  50. package/dist/packem_shared/types.d-CbYtFBw9.d.mts +1376 -0
  51. package/dist/packem_shared/types.d-CbYtFBw9.d.ts +1376 -0
  52. package/dist/packem_shared/voice-turn-DZNbOsWB.mjs +1 -0
  53. package/dist/packem_shared/webSearchTool-BptEsfd9.mjs +1 -0
  54. package/dist/packem_shared/workflow-binding-Dm9hBzx_.mjs +1 -0
  55. package/dist/reply.d.mts +40 -0
  56. package/dist/reply.d.ts +40 -0
  57. package/dist/reply.mjs +1 -0
  58. package/dist/sandbox.d.mts +269 -124
  59. package/dist/sandbox.d.ts +269 -124
  60. package/dist/sandbox.mjs +1 -109
  61. package/dist/skill-markdown.d.mts +36 -0
  62. package/dist/skill-markdown.d.ts +36 -0
  63. package/dist/skill-markdown.mjs +1 -0
  64. package/dist/telemetry/index.d.mts +314 -114
  65. package/dist/telemetry/index.d.ts +314 -114
  66. package/dist/telemetry/index.mjs +1 -4
  67. package/package.json +18 -9
  68. package/dist/packem_shared/AGENT_MODULE-Dnt_-AAT.mjs +0 -24
  69. package/dist/packem_shared/VoiceSessionDO-DLoXsHGF.mjs +0 -297
  70. package/dist/packem_shared/adaptMcpResult-wtNMvLoP.mjs +0 -65
  71. package/dist/packem_shared/agentAsTool-Dt8NlU6k.mjs +0 -94
  72. package/dist/packem_shared/base64-BVwtgRJV.mjs +0 -18
  73. package/dist/packem_shared/braintrustTelemetry-wuGDErob.mjs +0 -47
  74. package/dist/packem_shared/buildModelMessages-BWFigaoo.mjs +0 -69
  75. package/dist/packem_shared/codeTool-CjgJOC9t.mjs +0 -122
  76. package/dist/packem_shared/collectAgenticMemoryTools-QrzpV-WX.mjs +0 -97
  77. package/dist/packem_shared/combineTelemetry-DCyaaWAI.mjs +0 -43
  78. package/dist/packem_shared/common-DAeFCot5.mjs +0 -61
  79. package/dist/packem_shared/compileAgentWorkflow-BxJjHgtD.mjs +0 -55
  80. package/dist/packem_shared/consoleTelemetry-z2MiP1jt.mjs +0 -93
  81. package/dist/packem_shared/createAgentContext-4xJGXNR4.mjs +0 -50
  82. package/dist/packem_shared/createAgentGenerate-BQv9YJ01.mjs +0 -192
  83. package/dist/packem_shared/createDispatchRunner-DSbp_dph-ZHTtxy3f.mjs +0 -69
  84. package/dist/packem_shared/defineAgent-D6maSbVc.mjs +0 -148
  85. package/dist/packem_shared/defineSkill-Ctf_S-rz.mjs +0 -22
  86. package/dist/packem_shared/functionTool-D6lCa2jB.mjs +0 -20
  87. package/dist/packem_shared/graph-component-aoUwO-f0.mjs +0 -216
  88. package/dist/packem_shared/memory-D4FPcBsX.mjs +0 -12
  89. package/dist/packem_shared/normalizeEntityName-CyEEWFkR.mjs +0 -3
  90. package/dist/packem_shared/runAgentLoop-Dhg4ZNvw.mjs +0 -493
  91. package/dist/packem_shared/runVoiceTurn-LnqLvCRR.mjs +0 -211
  92. package/dist/packem_shared/sandboxComponent-DR3pTwBL.mjs +0 -194
  93. package/dist/packem_shared/sentryTelemetry-CgqFJyLO.mjs +0 -36
  94. package/dist/packem_shared/types.d-BhJFTvz_.d.mts +0 -1114
  95. package/dist/packem_shared/types.d-BhJFTvz_.d.ts +0 -1114
@@ -1,13 +1,13 @@
1
- import { A as AgentDefinition } from "./packem_shared/types.d-BhJFTvz_.mjs";
2
- export type { I as InboundChannelEvent } from "./packem_shared/types.d-BhJFTvz_.mjs";
1
+ import { A as AgentDefinition } from "./packem_shared/types.d-CbYtFBw9.mjs";
2
+ export type { I as InboundChannelEvent } from "./packem_shared/types.d-CbYtFBw9.mjs";
3
3
  import '@lunora/mail/inbound';
4
4
  import 'ai';
5
5
  /**
6
- * Verify a Slack request signature (`x-slack-signature` = `v0=` + HMAC over
7
- * `v0:timestamp:body`), rejecting a stale timestamp to bound replay. `now` is
8
- * injectable for deterministic tests (defaults to the wall clock).
9
- * @experimental
10
- */
6
+ * Verify a Slack request signature (`x-slack-signature` = `v0=` + HMAC over
7
+ * `v0:timestamp:body`), rejecting a stale timestamp to bound replay. `now` is
8
+ * injectable for deterministic tests (defaults to the wall clock).
9
+ * @experimental
10
+ */
11
11
  declare const verifySlack: (options: {
12
12
  body: string;
13
13
  now?: number;
@@ -17,50 +17,69 @@ declare const verifySlack: (options: {
17
17
  tolerance?: number;
18
18
  }) => Promise<boolean>;
19
19
  /**
20
- * Verify a GitHub webhook signature (`x-hub-signature-256` = `sha256=` + HMAC over the body).
21
- * @experimental
22
- */
20
+ * Verify a GitHub webhook signature (`x-hub-signature-256` = `sha256=` + HMAC over the body).
21
+ *
22
+ * There is no replay window: GitHub signs the body alone, with no timestamp, so
23
+ * a captured delivery verifies indefinitely. `dispatchAgentChannel` bounds that
24
+ * by keying the run on the SHA-256 of the signed body (see `deliveryId`), so a
25
+ * replay dedupes to the original run — for as long as the Workflow keeps that
26
+ * instance id.
27
+ * @experimental
28
+ */
23
29
  declare const verifyGithub: (options: {
24
30
  body: string;
25
31
  secret: string;
26
32
  signature: string | undefined;
27
33
  }) => Promise<boolean>;
28
34
  /**
29
- * Verify a Discord interaction signature: Ed25519 over `timestamp + body`,
30
- * `x-signature-ed25519` (hex) against the application's `publicKey` (hex).
31
- * @experimental
32
- */
35
+ * Verify a Discord interaction signature: Ed25519 over `timestamp + body`,
36
+ * `x-signature-ed25519` (hex) against the application's `publicKey` (hex).
37
+ * The signed `x-signature-timestamp` must be within `tolerance` seconds of
38
+ * `now` in either direction, or a captured interaction would verify forever.
39
+ * `now` is injectable for deterministic tests (defaults to the wall clock).
40
+ * @experimental
41
+ */
33
42
  declare const verifyDiscord: (options: {
34
43
  body: string;
44
+ now?: number;
35
45
  publicKey: string;
36
46
  signature: string | undefined;
37
47
  timestamp: string | undefined;
48
+ tolerance?: number;
38
49
  }) => Promise<boolean>;
39
50
  /**
40
- * One agent wired into the inbound channel HTTP handler.
41
- * @experimental
42
- */
51
+ * One agent wired into the inbound channel HTTP handler.
52
+ * @experimental
53
+ */
43
54
  interface AgentChannelTarget {
44
55
  /** The agent definition — only its `onInbound` config is read. */
45
56
  agent: Pick<AgentDefinition, "onInbound">;
46
- /** The `AGENT_*` Workflow binding name (off `env`) that starts a run. */
47
- binding: string;
57
+ /** The agent's export key (its generated class name), resolved off `ctx.exports` or `env`. */
58
+ className: string;
48
59
  }
49
60
  /**
50
- * The HTTP handler `dispatchAgentChannel` returns — mount it on a webhook route.
51
- * @experimental
52
- */
53
- type InboundChannelHandler = (request: Request, env: Record<string, unknown>) => Promise<Response>;
61
+ * The HTTP handler `dispatchAgentChannel` returns — mount it on a webhook route.
62
+ * @experimental
63
+ */
64
+ /**
65
+ * A Worker `fetch`-shaped handler. The Worker `ctx` is required: on Cloudflare
66
+ * the agent is reached as `ctx.exports.<Class>`, so a handler mounted without it
67
+ * could never start a run (from an `httpRouter` route: `handler(c.req.raw,
68
+ * c.env, c.executionCtx)`).
69
+ */
70
+ type InboundChannelHandler = (request: Request, env: Record<string, unknown>, context: {
71
+ exports?: unknown;
72
+ }) => Promise<Response>;
54
73
  /**
55
- * Build an HTTP handler that starts a durable agent run from a verified inbound
56
- * webhook. The channel is detected from the signature headers; EACH eligible
57
- * target is verified against ITS OWN secret before its mapper is offered the
58
- * event (so one app's valid signature can't trigger another app's agent), and
59
- * the first target that both verifies and claims starts a run on its Workflow
60
- * binding. Returns `401` when NO target's signature verifies, `200` on a claim
61
- * (or a Discord PONG), `204` when a verified event is declined by every mapper,
62
- * and `400` for an unrecognized webhook.
63
- * @experimental
64
- */
74
+ * Build an HTTP handler that starts a durable agent run from a verified inbound
75
+ * webhook. The channel is detected from the signature headers; EACH eligible
76
+ * target is verified against ITS OWN secret before its mapper is offered the
77
+ * event (so one app's valid signature can't trigger another app's agent), and
78
+ * the first target that both verifies and claims starts a run on its Workflow
79
+ * binding. Returns `401` when NO target's signature verifies, `200` on a claim
80
+ * (or a Discord PONG), `204` when a verified event is declined by every mapper,
81
+ * and `400` for an unrecognized webhook.
82
+ * @experimental
83
+ */
65
84
  declare const dispatchAgentChannel: (targets: ReadonlyArray<AgentChannelTarget>) => InboundChannelHandler;
66
85
  export { type AgentChannelTarget, type InboundChannelHandler, dispatchAgentChannel, verifyDiscord, verifyGithub, verifySlack };
@@ -1,13 +1,13 @@
1
- import { A as AgentDefinition } from "./packem_shared/types.d-BhJFTvz_.js";
2
- export type { I as InboundChannelEvent } from "./packem_shared/types.d-BhJFTvz_.js";
1
+ import { A as AgentDefinition } from "./packem_shared/types.d-CbYtFBw9.js";
2
+ export type { I as InboundChannelEvent } from "./packem_shared/types.d-CbYtFBw9.js";
3
3
  import '@lunora/mail/inbound';
4
4
  import 'ai';
5
5
  /**
6
- * Verify a Slack request signature (`x-slack-signature` = `v0=` + HMAC over
7
- * `v0:timestamp:body`), rejecting a stale timestamp to bound replay. `now` is
8
- * injectable for deterministic tests (defaults to the wall clock).
9
- * @experimental
10
- */
6
+ * Verify a Slack request signature (`x-slack-signature` = `v0=` + HMAC over
7
+ * `v0:timestamp:body`), rejecting a stale timestamp to bound replay. `now` is
8
+ * injectable for deterministic tests (defaults to the wall clock).
9
+ * @experimental
10
+ */
11
11
  declare const verifySlack: (options: {
12
12
  body: string;
13
13
  now?: number;
@@ -17,50 +17,69 @@ declare const verifySlack: (options: {
17
17
  tolerance?: number;
18
18
  }) => Promise<boolean>;
19
19
  /**
20
- * Verify a GitHub webhook signature (`x-hub-signature-256` = `sha256=` + HMAC over the body).
21
- * @experimental
22
- */
20
+ * Verify a GitHub webhook signature (`x-hub-signature-256` = `sha256=` + HMAC over the body).
21
+ *
22
+ * There is no replay window: GitHub signs the body alone, with no timestamp, so
23
+ * a captured delivery verifies indefinitely. `dispatchAgentChannel` bounds that
24
+ * by keying the run on the SHA-256 of the signed body (see `deliveryId`), so a
25
+ * replay dedupes to the original run — for as long as the Workflow keeps that
26
+ * instance id.
27
+ * @experimental
28
+ */
23
29
  declare const verifyGithub: (options: {
24
30
  body: string;
25
31
  secret: string;
26
32
  signature: string | undefined;
27
33
  }) => Promise<boolean>;
28
34
  /**
29
- * Verify a Discord interaction signature: Ed25519 over `timestamp + body`,
30
- * `x-signature-ed25519` (hex) against the application's `publicKey` (hex).
31
- * @experimental
32
- */
35
+ * Verify a Discord interaction signature: Ed25519 over `timestamp + body`,
36
+ * `x-signature-ed25519` (hex) against the application's `publicKey` (hex).
37
+ * The signed `x-signature-timestamp` must be within `tolerance` seconds of
38
+ * `now` in either direction, or a captured interaction would verify forever.
39
+ * `now` is injectable for deterministic tests (defaults to the wall clock).
40
+ * @experimental
41
+ */
33
42
  declare const verifyDiscord: (options: {
34
43
  body: string;
44
+ now?: number;
35
45
  publicKey: string;
36
46
  signature: string | undefined;
37
47
  timestamp: string | undefined;
48
+ tolerance?: number;
38
49
  }) => Promise<boolean>;
39
50
  /**
40
- * One agent wired into the inbound channel HTTP handler.
41
- * @experimental
42
- */
51
+ * One agent wired into the inbound channel HTTP handler.
52
+ * @experimental
53
+ */
43
54
  interface AgentChannelTarget {
44
55
  /** The agent definition — only its `onInbound` config is read. */
45
56
  agent: Pick<AgentDefinition, "onInbound">;
46
- /** The `AGENT_*` Workflow binding name (off `env`) that starts a run. */
47
- binding: string;
57
+ /** The agent's export key (its generated class name), resolved off `ctx.exports` or `env`. */
58
+ className: string;
48
59
  }
49
60
  /**
50
- * The HTTP handler `dispatchAgentChannel` returns — mount it on a webhook route.
51
- * @experimental
52
- */
53
- type InboundChannelHandler = (request: Request, env: Record<string, unknown>) => Promise<Response>;
61
+ * The HTTP handler `dispatchAgentChannel` returns — mount it on a webhook route.
62
+ * @experimental
63
+ */
64
+ /**
65
+ * A Worker `fetch`-shaped handler. The Worker `ctx` is required: on Cloudflare
66
+ * the agent is reached as `ctx.exports.<Class>`, so a handler mounted without it
67
+ * could never start a run (from an `httpRouter` route: `handler(c.req.raw,
68
+ * c.env, c.executionCtx)`).
69
+ */
70
+ type InboundChannelHandler = (request: Request, env: Record<string, unknown>, context: {
71
+ exports?: unknown;
72
+ }) => Promise<Response>;
54
73
  /**
55
- * Build an HTTP handler that starts a durable agent run from a verified inbound
56
- * webhook. The channel is detected from the signature headers; EACH eligible
57
- * target is verified against ITS OWN secret before its mapper is offered the
58
- * event (so one app's valid signature can't trigger another app's agent), and
59
- * the first target that both verifies and claims starts a run on its Workflow
60
- * binding. Returns `401` when NO target's signature verifies, `200` on a claim
61
- * (or a Discord PONG), `204` when a verified event is declined by every mapper,
62
- * and `400` for an unrecognized webhook.
63
- * @experimental
64
- */
74
+ * Build an HTTP handler that starts a durable agent run from a verified inbound
75
+ * webhook. The channel is detected from the signature headers; EACH eligible
76
+ * target is verified against ITS OWN secret before its mapper is offered the
77
+ * event (so one app's valid signature can't trigger another app's agent), and
78
+ * the first target that both verifies and claims starts a run on its Workflow
79
+ * binding. Returns `401` when NO target's signature verifies, `200` on a claim
80
+ * (or a Discord PONG), `204` when a verified event is declined by every mapper,
81
+ * and `400` for an unrecognized webhook.
82
+ * @experimental
83
+ */
65
84
  declare const dispatchAgentChannel: (targets: ReadonlyArray<AgentChannelTarget>) => InboundChannelHandler;
66
85
  export { type AgentChannelTarget, type InboundChannelHandler, dispatchAgentChannel, verifyDiscord, verifyGithub, verifySlack };
package/dist/channels.mjs CHANGED
@@ -1,181 +1 @@
1
- import { LunoraError } from '@lunora/errors';
2
-
3
- const DEFAULT_TIMESTAMP_TOLERANCE = 300;
4
- const NON_HEX = /[^0-9a-f]/iu;
5
- const encoder = new TextEncoder();
6
- const utf8 = (value) => new Uint8Array(encoder.encode(value));
7
- const hexToBytes = (hex) => {
8
- if (hex.length % 2 !== 0 || NON_HEX.test(hex)) {
9
- throw new LunoraError("BAD_REQUEST", "@lunora/agent: malformed hex signature");
10
- }
11
- const bytes = new Uint8Array(hex.length / 2);
12
- for (let index = 0; index < bytes.length; index += 1) {
13
- bytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16);
14
- }
15
- return bytes;
16
- };
17
- const verifyHmacSha256 = async (secret, message, signatureHex) => {
18
- try {
19
- const key = await crypto.subtle.importKey("raw", utf8(secret), { hash: "SHA-256", name: "HMAC" }, false, ["verify"]);
20
- return await crypto.subtle.verify("HMAC", key, hexToBytes(signatureHex), utf8(message));
21
- } catch {
22
- return false;
23
- }
24
- };
25
- const isFreshTimestamp = (timestampSeconds, nowSeconds, tolerance) => Number.isFinite(timestampSeconds) && Math.abs(nowSeconds - timestampSeconds) <= tolerance;
26
- const verifySlack = async (options) => {
27
- const { body, now = Date.now() / 1e3, signature, signingSecret, timestamp, tolerance = DEFAULT_TIMESTAMP_TOLERANCE } = options;
28
- if (!signature || !timestamp || !signature.startsWith("v0=")) {
29
- return false;
30
- }
31
- if (!isFreshTimestamp(Number(timestamp), now, tolerance)) {
32
- return false;
33
- }
34
- return verifyHmacSha256(signingSecret, `v0:${timestamp}:${body}`, signature.slice("v0=".length));
35
- };
36
- const verifyGithub = async (options) => {
37
- const { body, secret, signature } = options;
38
- if (!signature?.startsWith("sha256=")) {
39
- return false;
40
- }
41
- return verifyHmacSha256(secret, body, signature.slice("sha256=".length));
42
- };
43
- const verifyDiscord = async (options) => {
44
- const { body, publicKey, signature, timestamp } = options;
45
- if (!signature || !timestamp) {
46
- return false;
47
- }
48
- try {
49
- const key = await crypto.subtle.importKey("raw", hexToBytes(publicKey), { name: "Ed25519" }, false, ["verify"]);
50
- return await crypto.subtle.verify({ name: "Ed25519" }, key, hexToBytes(signature), utf8(timestamp + body));
51
- } catch {
52
- return false;
53
- }
54
- };
55
- const detectChannel = (headers) => {
56
- if (headers.has("x-slack-signature")) {
57
- return "slack";
58
- }
59
- if (headers.has("x-hub-signature-256")) {
60
- return "github";
61
- }
62
- if (headers.has("x-signature-ed25519")) {
63
- return "discord";
64
- }
65
- return void 0;
66
- };
67
- const resolveSecret = (secret, env) => {
68
- if (typeof secret === "function") {
69
- return secret(env);
70
- }
71
- const value = env[secret];
72
- return typeof value === "string" ? value : void 0;
73
- };
74
- const verifyChannel = async (channel, secret, headers, body) => {
75
- switch (channel) {
76
- case "discord": {
77
- return verifyDiscord({
78
- body,
79
- publicKey: secret,
80
- signature: headers.get("x-signature-ed25519") ?? void 0,
81
- timestamp: headers.get("x-signature-timestamp") ?? void 0
82
- });
83
- }
84
- case "github": {
85
- return verifyGithub({ body, secret, signature: headers.get("x-hub-signature-256") ?? void 0 });
86
- }
87
- case "slack": {
88
- return verifySlack({
89
- body,
90
- signature: headers.get("x-slack-signature") ?? void 0,
91
- signingSecret: secret,
92
- timestamp: headers.get("x-slack-request-timestamp") ?? void 0
93
- });
94
- }
95
- default: {
96
- return false;
97
- }
98
- }
99
- };
100
- const discordPongResponse = (channel, body) => {
101
- if (channel !== "discord") {
102
- return void 0;
103
- }
104
- try {
105
- if (JSON.parse(body).type === 1) {
106
- return Response.json({ type: 1 });
107
- }
108
- } catch {
109
- }
110
- return void 0;
111
- };
112
- const UNSAFE_INSTANCE_ID = /[^\w-]/gu;
113
- const DUPLICATE_INSTANCE = /already[\s-]?exists/iu;
114
- const ack = () => new Response(void 0, { status: 200 });
115
- const isDuplicateInstanceError = (error) => DUPLICATE_INSTANCE.test(error instanceof Error ? error.message : String(error));
116
- const deliveryId = (channel, headers, body) => {
117
- if (channel === "github") {
118
- return headers.get("x-github-delivery") ?? void 0;
119
- }
120
- try {
121
- const parsed = JSON.parse(body);
122
- const raw = channel === "slack" ? parsed.event_id : parsed.id;
123
- return typeof raw === "string" ? raw : void 0;
124
- } catch {
125
- return void 0;
126
- }
127
- };
128
- const startChannelRun = async (workflow, run, channel, id) => {
129
- const sanitizedId = id === void 0 ? "" : id.replaceAll(UNSAFE_INSTANCE_ID, "");
130
- if (sanitizedId === "") {
131
- await workflow.create({ params: run });
132
- return ack();
133
- }
134
- try {
135
- await workflow.create({ id: `${channel}-${sanitizedId}`.slice(0, 60), params: run });
136
- } catch (error) {
137
- if (isDuplicateInstanceError(error)) {
138
- return ack();
139
- }
140
- throw error;
141
- }
142
- return ack();
143
- };
144
- const dispatchAgentChannel = (targets) => async (request, env) => {
145
- const body = await request.text();
146
- const channel = detectChannel(request.headers);
147
- if (channel === void 0) {
148
- return new Response("Unrecognized webhook", { status: 400 });
149
- }
150
- const eligible = targets.map((target) => {
151
- return { config: target.agent.onInbound, target };
152
- }).filter((entry) => entry.config?.channel === channel);
153
- const event = { channel, headers: request.headers, json: () => JSON.parse(body), rawBody: body };
154
- let verifiedAny = false;
155
- for (const { config, target } of eligible) {
156
- const secret = resolveSecret(config.secret, env);
157
- if (secret === void 0 || !await verifyChannel(channel, secret, request.headers, body)) {
158
- continue;
159
- }
160
- verifiedAny = true;
161
- const pong = discordPongResponse(channel, body);
162
- if (pong) {
163
- return pong;
164
- }
165
- const run = await config.map(event);
166
- if (!run) {
167
- continue;
168
- }
169
- const workflow = env[target.binding];
170
- if (!workflow || typeof workflow.create !== "function") {
171
- throw new LunoraError(
172
- "INTERNAL",
173
- `@lunora/agent: no Workflow binding "${target.binding}" on env for an inbound-channel agent — run codegen/dev so wrangler.jsonc declares it`
174
- );
175
- }
176
- return await startChannelRun(workflow, run, channel, deliveryId(channel, request.headers, body));
177
- }
178
- return verifiedAny ? new Response(void 0, { status: 204 }) : new Response("Invalid signature", { status: 401 });
179
- };
180
-
181
- export { dispatchAgentChannel, verifyDiscord, verifyGithub, verifySlack };
1
+ import{LunoraError as l}from"@lunora/errors";import{isDuplicateInstanceError as A}from"@lunora/workflow";import{h as x,B as N}from"./packem_shared/branch-marker-boZ00zmk.mjs";import{f as R}from"./packem_shared/fnv1a-BNN96GYb.mjs";import{r as k}from"./packem_shared/workflow-binding-Dm9hBzx_.mjs";const v=300,S=/[^0-9a-f]/iu,T=new TextEncoder,c=t=>new Uint8Array(T.encode(t)),f=t=>{if(t.length%2!==0||S.test(t))throw new l("BAD_REQUEST","@lunora/agent: malformed hex signature");const e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n+=1)e[n]=Number.parseInt(t.slice(n*2,n*2+2),16);return e},b=async(t,e,n)=>{try{const r=await crypto.subtle.importKey("raw",c(t),{hash:"SHA-256",name:"HMAC"},!1,["verify"]);return await crypto.subtle.verify("HMAC",r,f(n),c(e))}catch{return!1}},E=(t,e,n)=>Number.isFinite(t)&&Math.abs(e-t)<=n,H=async t=>{const{body:e,now:n=Date.now()/1e3,signature:r,signingSecret:a,timestamp:s,tolerance:i=v}=t;return!r||!s||!r.startsWith("v0=")||!E(Number(s),n,i)?!1:b(a,`v0:${s}:${e}`,r.slice(3))},C=async t=>{const{body:e,secret:n,signature:r}=t;return r?.startsWith("sha256=")?b(n,e,r.slice(7)):!1},I=async t=>{const{body:e,now:n=Date.now()/1e3,publicKey:r,signature:a,timestamp:s,tolerance:i=v}=t;if(!a||!s||!E(Number(s),n,i))return!1;try{const u=await crypto.subtle.importKey("raw",f(r),{name:"Ed25519"},!1,["verify"]);return await crypto.subtle.verify({name:"Ed25519"},u,f(a),c(s+e))}catch{return!1}},_=t=>{if(t.has("x-slack-signature"))return"slack";if(t.has("x-hub-signature-256"))return"github";if(t.has("x-signature-ed25519"))return"discord"},B=(t,e)=>{if(typeof t=="function")return t(e);const n=e[t];return typeof n=="string"?n:void 0},D=async(t,e,n,r)=>{switch(t){case"discord":return I({body:r,publicKey:e,signature:n.get("x-signature-ed25519")??void 0,timestamp:n.get("x-signature-timestamp")??void 0});case"github":return C({body:r,secret:e,signature:n.get("x-hub-signature-256")??void 0});case"slack":return H({body:r,signature:n.get("x-slack-signature")??void 0,signingSecret:e,timestamp:n.get("x-slack-request-timestamp")??void 0});default:return!1}},M=(t,e)=>{if(t==="discord")try{if(JSON.parse(e).type===1)return Response.json({type:1})}catch{}},w=()=>new Response(void 0,{status:200}),U=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",c(t)))].map(e=>e.toString(16).padStart(2,"0")).join(""),O=async(t,e)=>{if(t!=="github")try{const n=JSON.parse(e),r=t==="slack"?n.event_id:n.id;if(typeof r=="string"&&r!=="")return r}catch{}return U(e)},$=async(t,e,n,r)=>{if(x(e))throw new l("BAD_REQUEST",`@lunora/agent: inbound channel run params ${N}`);try{await t.create({id:`${n}-${R(r)}`,params:e})}catch(a){if(A(a))return w();throw a}return w()},W=t=>async(e,n,r)=>{const a=await e.text(),s=_(e.headers);if(s===void 0)return new Response("Unrecognized webhook",{status:400});const i=t.map(o=>({config:o.agent.onInbound,target:o})).filter(o=>o.config?.channel===s),u={channel:s,headers:e.headers,json:()=>JSON.parse(a),rawBody:a};let d=!1;for(const{config:o,target:g}of i){const p=B(o.secret,n);if(p===void 0||!await D(s,p,e.headers,a))continue;d=!0;const y=M(s,a);if(y)return y;const h=await o.map(u);if(!h)continue;const m=k(n,r.exports,g.className,["create"]);if(m===void 0)throw new l("INTERNAL",`@lunora/agent: no "${g.className}" on ctx.exports or env for an inbound-channel agent — run codegen/dev so wrangler.jsonc declares it`);return await $(m,h,s,await O(s,a))}return d?new Response(void 0,{status:204}):new Response("Invalid signature",{status:401})};export{W as dispatchAgentChannel,I as verifyDiscord,C as verifyGithub,H as verifySlack};
@@ -1,33 +1,61 @@
1
- import { SchemaExtension } from '@lunora/server';
1
+ import { TableDefinition, SchemaExtension } from '@lunora/server';
2
+ /** The schema-extension key the agent tables merge under (`agent_*` physical names). */
3
+ declare const AGENT_EXTENSION_KEY: "agent";
2
4
  /**
3
- * Loose structural view of a registered Lunora function — wide enough for any
4
- * concrete `RegisteredMutation`/`RegisteredQuery` (whose precise validator-map
5
- * generics make them invariant), narrow enough for re-export, dispatch, and
6
- * tests. Codegen registers the runtime value; it never needs the generics.
7
- */
5
+ * Loose structural view of a registered Lunora function — wide enough for any
6
+ * concrete `RegisteredMutation`/`RegisteredQuery` (whose precise validator-map
7
+ * generics make them invariant), narrow enough for re-export, dispatch, and
8
+ * tests. Codegen registers the runtime value; it never needs the generics.
9
+ */
8
10
  interface AgentRegisteredFunction {
9
11
  readonly args: unknown;
10
12
  readonly handler: (context: unknown, args: never) => unknown;
11
13
  readonly kind: "mutation" | "query";
12
14
  readonly visibility?: "internal" | "public";
13
15
  }
14
- /** Stamp a registered function internal — server-side callable only. */
15
-
16
16
  /**
17
- * The per-owner dedup key for an entity name: trim, collapse internal
18
- * whitespace, lowercase. Deterministic (no locale) so a workflow replay or
19
- * retry writes the exact same key — the graph upsert stays idempotent.
20
- * @experimental
21
- */
17
+ * The episodic-memory table, spread into the `agent` schema extension by
18
+ * `component.ts`. Owner-scoped (keyed by `owner`, not thread), so a run in one
19
+ * conversation recalls the timeline of the user's earlier runs across every
20
+ * thread. `.public()` + RLS-exempt like the thread/graph tables (package code,
21
+ * access-controlled inside the dispatched functions).
22
+ *
23
+ * Explicitly typed as a `Record` of `TableDefinition` values for the same
24
+ * `--isolatedDeclarations` reason as `graphTables` (an exported const with a
25
+ * computed key can't be inferred; see graph-component.ts).
26
+ */
27
+ declare const episodeTables: Record<"episodes", TableDefinition>;
28
+ /** Bare table names — auto-prefixed with the extension key at merge time. */
29
+ declare const ENTITIES_BARE_TABLE = "entities";
30
+ declare const EDGES_BARE_TABLE = "edges";
31
+ /**
32
+ * The graph-memory tables, spread into the `agent` schema extension by
33
+ * `component.ts`. Owner-scoped (keyed by `owner`, not thread) so knowledge
34
+ * extracted in one conversation is traversable in the next, and `.public()` +
35
+ * RLS-exempt like the thread tables (package code, access-controlled inside the
36
+ * dispatched functions).
37
+ *
38
+ * Explicitly typed as a `Record` of `TableDefinition` values over its bare names
39
+ * because it is an EXPORTED const with computed (`[BARE]`) keys — under
40
+ * `--isolatedDeclarations` (packem's `.d.ts` emit) a bare exported object literal
41
+ * with computed keys can't have its type inferred (TS9038). The names stay
42
+ * literal so `.extend(agentExtension)` adds exact table names; row types come
43
+ * from codegen.
44
+ */
45
+ declare const graphTables: Record<typeof EDGES_BARE_TABLE | typeof ENTITIES_BARE_TABLE, TableDefinition>;
46
+ /**
47
+ * The per-owner dedup key for an entity name: trim, collapse internal
48
+ * whitespace, lowercase. Deterministic (no locale) so a workflow replay or
49
+ * retry writes the exact same key — the graph upsert stays idempotent.
50
+ * @experimental
51
+ */
22
52
  declare const normalizeEntityName: (name: string) => string;
23
- /** The two internal graph-memory functions the durable loop dispatches to. */
24
-
25
53
  /**
26
- * Loose structural view of the registered sandbox action — wide enough for the
27
- * concrete `RegisteredAction`, narrow enough for re-export + dispatch. Codegen
28
- * registers the runtime value; it never needs the precise generics.
29
- * @experimental
30
- */
54
+ * Loose structural view of the registered sandbox action — wide enough for the
55
+ * concrete `RegisteredAction`, narrow enough for re-export + dispatch. Codegen
56
+ * registers the runtime value; it never needs the precise generics.
57
+ * @experimental
58
+ */
31
59
  interface SandboxRegisteredFunction {
32
60
  readonly args: unknown;
33
61
  readonly handler: (context: unknown, args: never) => unknown;
@@ -35,54 +63,53 @@ interface SandboxRegisteredFunction {
35
63
  readonly visibility?: "internal" | "public";
36
64
  }
37
65
  /**
38
- * `SandboxComponent` is part of the experimental `@lunora/agent` API and may change without a major version bump.
39
- * @experimental
40
- */
66
+ * `SandboxComponent` is part of the experimental `@lunora/agent` API and may change without a major version bump.
67
+ * @experimental
68
+ */
41
69
  interface SandboxComponent {
42
70
  invoke: SandboxRegisteredFunction;
43
71
  }
44
72
  /**
45
- * Resolve a model-supplied `path` to an absolute R2 key UNDER `root`, rejecting
46
- * any `..` that would escape the sandbox root. Every returned key is guaranteed
47
- * to start with the normalized `root`, so the model can never read or write
48
- * outside its own prefix — the fs sandbox's core isolation guarantee.
49
- */
50
-
51
- /**
52
- * Build the sandbox runtime component: the single internal action the
53
- * batteries-included `browserTool`/`containerTool` dispatch to. Codegen
54
- * auto-registers it at `sandbox:invoke` whenever `lunora/` imports a sandbox
55
- * tool. It runs as an **action** because that is the only ctx codegen attaches
56
- * `ctx.browser` to (and `ctx.containers` rides every ctx once a container is
57
- * declared) — the durable tool step itself has neither.
58
- * @experimental
59
- */
73
+ * Build the sandbox runtime component: the single internal action the
74
+ * batteries-included `browserTool`/`containerTool` dispatch to. Codegen
75
+ * auto-registers it at `sandbox:invoke` whenever `lunora/` imports a sandbox
76
+ * tool. It runs as an **action** because that is the only ctx codegen attaches
77
+ * `ctx.browser` to (and `ctx.containers` rides every ctx once a container is
78
+ * declared) — the durable tool step itself has neither.
79
+ * @experimental
80
+ */
60
81
  declare const sandboxComponent: () => SandboxComponent;
82
+ /** Bare table names — auto-prefixed with the extension key at merge time. */
83
+ declare const THREADS_BARE_TABLE = "threads";
84
+ declare const MESSAGES_BARE_TABLE = "messages";
85
+ declare const RUN_QUEUE_BARE_TABLE = "run_queue";
61
86
  /**
62
- * The agent thread tables, shipped as a schema extension so an app merges
63
- * them with one call and they can never collide with app tables:
64
- *
65
- * ```ts
66
- * // lunora/schema.ts
67
- * export default defineSchema({ ... }).extend(agentExtension);
68
- * ```
69
- *
70
- * Message ordering follows the Convex-agent model: `seq` is the monotonic
71
- * per-thread position (allocated from the thread's `messageCount` counter, so
72
- * allocation is O(1) inside the serialized mutation), and `messageKey` is the
73
- * deterministic idempotency key — a workflow replay that re-persists the same
74
- * message is a no-op instead of a duplicate.
75
- * @experimental
76
- */
77
- declare const agentExtension: SchemaExtension;
87
+ * The agent thread tables, shipped as a schema extension so an app merges
88
+ * them with one call and they can never collide with app tables:
89
+ *
90
+ * ```ts
91
+ * // lunora/schema.ts
92
+ * export default defineSchema({ ... }).extend(agentExtension);
93
+ * ```
94
+ *
95
+ * Message ordering follows the Convex-agent model: `seq` is the monotonic
96
+ * per-thread position (allocated from the thread's `messageCount` counter, so
97
+ * allocation is O(1) inside the serialized mutation), and `messageKey` is the
98
+ * deterministic idempotency key — a workflow replay that re-persists the same
99
+ * message is a no-op instead of a duplicate.
100
+ * @experimental
101
+ */
102
+ declare const agentExtension: SchemaExtension<Record<keyof typeof episodeTables | keyof typeof graphTables | typeof MESSAGES_BARE_TABLE | typeof RUN_QUEUE_BARE_TABLE | typeof THREADS_BARE_TABLE, TableDefinition>, typeof AGENT_EXTENSION_KEY>;
78
103
  /**
79
- * `AgentComponent` is part of the experimental `@lunora/agent` API and may change without a major version bump.
80
- * @experimental
81
- */
104
+ * `AgentComponent` is part of the experimental `@lunora/agent` API and may change without a major version bump.
105
+ * @experimental
106
+ */
82
107
  interface AgentComponent {
83
108
  extension: SchemaExtension;
84
109
  functions: {
85
110
  agentAppendMessage: AgentRegisteredFunction;
111
+ agentCompleteRun: AgentRegisteredFunction;
112
+ agentDeleteMessage: AgentRegisteredFunction;
86
113
  agentEnsureThread: AgentRegisteredFunction;
87
114
  agentEpisodeRecall: AgentRegisteredFunction;
88
115
  agentEpisodeUpsert: AgentRegisteredFunction;
@@ -98,18 +125,18 @@ interface AgentComponent {
98
125
  };
99
126
  }
100
127
  /**
101
- * Build the agent runtime component: the thread schema extension plus the
102
- * functions the durable loop dispatches to (and the client subscribes to).
103
- * Codegen auto-registers them under the `agents:*` namespace whenever
104
- * `lunora/agents.ts` declares an agent — the loop's dispatch paths assume
105
- * that namespace, and apps never re-export these by hand.
106
- *
107
- * Most mutations are **internal** (only the workflow's admin-authenticated
108
- * dispatch may call them); the queries are public so a client can subscribe
109
- * to `agents:agentMessages` for a live thread view. Two mutations are public:
110
- * `agentResolveApproval` (a client resolves a HITL approval) and `agentRun`
111
- * (an HTTP client starts a durable run) — both owner-gated.
112
- * @experimental
113
- */
128
+ * Build the agent runtime component: the thread schema extension plus the
129
+ * functions the durable loop dispatches to (and the client subscribes to).
130
+ * Codegen auto-registers them under the `agents:*` namespace whenever
131
+ * `lunora/agents.ts` declares an agent — the loop's dispatch paths assume
132
+ * that namespace, and apps never re-export these by hand.
133
+ *
134
+ * Most mutations are **internal** (only the workflow's admin-authenticated
135
+ * dispatch may call them); the queries are public so a client can subscribe
136
+ * to `agents:agentMessages` for a live thread view. Two mutations are public:
137
+ * `agentResolveApproval` (a client resolves a HITL approval) and `agentRun`
138
+ * (an HTTP client starts a durable run) — both owner-gated.
139
+ * @experimental
140
+ */
114
141
  declare const agentComponent: () => AgentComponent;
115
142
  export { AgentComponent, type SandboxComponent, type SandboxRegisteredFunction, agentComponent, agentExtension, normalizeEntityName, sandboxComponent };