@agent-native/core 0.71.0 → 0.72.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 (165) hide show
  1. package/corpus/README.md +2 -2
  2. package/corpus/core/CHANGELOG.md +60 -0
  3. package/corpus/core/docs/content/actions.md +23 -0
  4. package/corpus/core/docs/content/audit-log.md +111 -0
  5. package/corpus/core/package.json +2 -1
  6. package/corpus/core/src/action.ts +80 -1
  7. package/corpus/core/src/agent/production-agent.ts +27 -0
  8. package/corpus/core/src/agent/run-store.ts +18 -1
  9. package/corpus/core/src/application-state/store.ts +5 -0
  10. package/corpus/core/src/audit/actions/get-audit-event.ts +23 -0
  11. package/corpus/core/src/audit/actions/list-audit-events.ts +65 -0
  12. package/corpus/core/src/audit/cleanup-job.ts +100 -0
  13. package/corpus/core/src/audit/config.ts +91 -0
  14. package/corpus/core/src/audit/index.ts +43 -0
  15. package/corpus/core/src/audit/record.ts +143 -0
  16. package/corpus/core/src/audit/redact.ts +109 -0
  17. package/corpus/core/src/audit/store.ts +244 -0
  18. package/corpus/core/src/audit/types.ts +125 -0
  19. package/corpus/core/src/chat-threads/store.ts +10 -0
  20. package/corpus/core/src/client/AssistantChat.tsx +6 -0
  21. package/corpus/core/src/client/chat/repo-helpers.ts +38 -0
  22. package/corpus/core/src/db/client.ts +4 -0
  23. package/corpus/core/src/db/widen-columns.ts +75 -0
  24. package/corpus/core/src/mcp/build-server.ts +1 -0
  25. package/corpus/core/src/oauth-tokens/store.ts +6 -0
  26. package/corpus/core/src/provider-api/custom-registry.ts +8 -0
  27. package/corpus/core/src/resources/store.ts +10 -0
  28. package/corpus/core/src/scripts/runner.ts +6 -3
  29. package/corpus/core/src/server/action-discovery.ts +6 -0
  30. package/corpus/core/src/server/action-routes.ts +1 -0
  31. package/corpus/core/src/server/auth.ts +5 -0
  32. package/corpus/core/src/server/core-routes-plugin.ts +14 -0
  33. package/corpus/core/src/server/security-headers.ts +9 -6
  34. package/corpus/core/src/settings/store.ts +6 -0
  35. package/corpus/core/src/templates/workspace-core/.agents/skills/audit-log/SKILL.md +93 -0
  36. package/corpus/core/src/usage/store.ts +6 -0
  37. package/corpus/templates/calendar/app/components/calendar/GoogleConnectBanner.tsx +60 -6
  38. package/corpus/templates/calendar/changelog/2026-06-23-added-a-heads-up-explaining-google-s-app-not-verified-screen.md +6 -0
  39. package/corpus/templates/clips/app/components/recorder/recorder-engine.ts +20 -43
  40. package/corpus/templates/clips/app/components/recorder/recording-toolbar.tsx +5 -1
  41. package/corpus/templates/clips/app/lib/countdown-audio-cue.ts +3 -51
  42. package/corpus/templates/clips/changelog/2026-06-23-public-clips-now-play-inline-in-slack-connect-a-workspac.md +6 -0
  43. package/corpus/templates/clips/chrome-extension/PERMISSIONS.md +72 -0
  44. package/corpus/templates/clips/chrome-extension/public/manifest.json +1 -10
  45. package/corpus/templates/clips/chrome-extension/src/background.ts +34 -1
  46. package/corpus/templates/clips/chrome-extension/src/content-script.ts +138 -11
  47. package/corpus/templates/clips/chrome-extension/src/offscreen.ts +50 -33
  48. package/corpus/templates/clips/chrome-extension/src/overlay.css +11 -27
  49. package/corpus/templates/clips/chrome-extension/src/overlay.html +7 -1
  50. package/corpus/templates/clips/chrome-extension/src/overlay.ts +33 -38
  51. package/corpus/templates/clips/chrome-extension/src/popup.ts +6 -24
  52. package/corpus/templates/clips/chrome-extension/vite.config.ts +5 -0
  53. package/corpus/templates/clips/desktop/src-tauri/src/native_screen.rs +43 -3
  54. package/corpus/templates/clips/server/lib/media-permissions.ts +5 -1
  55. package/corpus/templates/clips/shared/recording-audio.ts +62 -0
  56. package/corpus/templates/clips/shared/recording-core.ts +94 -0
  57. package/dist/action.d.ts +31 -0
  58. package/dist/action.d.ts.map +1 -1
  59. package/dist/action.js +45 -1
  60. package/dist/action.js.map +1 -1
  61. package/dist/agent/context-xray/schema.d.ts +1 -1
  62. package/dist/agent/observational-memory/schema.d.ts +1 -1
  63. package/dist/agent/production-agent.d.ts.map +1 -1
  64. package/dist/agent/production-agent.js +28 -0
  65. package/dist/agent/production-agent.js.map +1 -1
  66. package/dist/agent/run-store.d.ts.map +1 -1
  67. package/dist/agent/run-store.js +18 -1
  68. package/dist/agent/run-store.js.map +1 -1
  69. package/dist/application-state/store.d.ts.map +1 -1
  70. package/dist/application-state/store.js +5 -0
  71. package/dist/application-state/store.js.map +1 -1
  72. package/dist/audit/actions/get-audit-event.d.ts +11 -0
  73. package/dist/audit/actions/get-audit-event.d.ts.map +1 -0
  74. package/dist/audit/actions/get-audit-event.js +22 -0
  75. package/dist/audit/actions/get-audit-event.js.map +1 -0
  76. package/dist/audit/actions/list-audit-events.d.ts +22 -0
  77. package/dist/audit/actions/list-audit-events.d.ts.map +1 -0
  78. package/dist/audit/actions/list-audit-events.js +61 -0
  79. package/dist/audit/actions/list-audit-events.js.map +1 -0
  80. package/dist/audit/cleanup-job.d.ts +12 -0
  81. package/dist/audit/cleanup-job.d.ts.map +1 -0
  82. package/dist/audit/cleanup-job.js +93 -0
  83. package/dist/audit/cleanup-job.js.map +1 -0
  84. package/dist/audit/config.d.ts +30 -0
  85. package/dist/audit/config.d.ts.map +1 -0
  86. package/dist/audit/config.js +65 -0
  87. package/dist/audit/config.js.map +1 -0
  88. package/dist/audit/index.d.ts +13 -0
  89. package/dist/audit/index.d.ts.map +1 -0
  90. package/dist/audit/index.js +6 -0
  91. package/dist/audit/index.js.map +1 -0
  92. package/dist/audit/record.d.ts +24 -0
  93. package/dist/audit/record.d.ts.map +1 -0
  94. package/dist/audit/record.js +106 -0
  95. package/dist/audit/record.js.map +1 -0
  96. package/dist/audit/redact.d.ts +28 -0
  97. package/dist/audit/redact.d.ts.map +1 -0
  98. package/dist/audit/redact.js +109 -0
  99. package/dist/audit/redact.js.map +1 -0
  100. package/dist/audit/store.d.ts +14 -0
  101. package/dist/audit/store.d.ts.map +1 -0
  102. package/dist/audit/store.js +219 -0
  103. package/dist/audit/store.js.map +1 -0
  104. package/dist/audit/types.d.ts +114 -0
  105. package/dist/audit/types.d.ts.map +1 -0
  106. package/dist/audit/types.js +15 -0
  107. package/dist/audit/types.js.map +1 -0
  108. package/dist/chat-threads/store.d.ts.map +1 -1
  109. package/dist/chat-threads/store.js +10 -0
  110. package/dist/chat-threads/store.js.map +1 -1
  111. package/dist/client/AssistantChat.d.ts.map +1 -1
  112. package/dist/client/AssistantChat.js +6 -1
  113. package/dist/client/AssistantChat.js.map +1 -1
  114. package/dist/client/chat/repo-helpers.d.ts +16 -0
  115. package/dist/client/chat/repo-helpers.d.ts.map +1 -1
  116. package/dist/client/chat/repo-helpers.js +40 -0
  117. package/dist/client/chat/repo-helpers.js.map +1 -1
  118. package/dist/db/client.d.ts.map +1 -1
  119. package/dist/db/client.js +3 -0
  120. package/dist/db/client.js.map +1 -1
  121. package/dist/db/widen-columns.d.ts +39 -0
  122. package/dist/db/widen-columns.d.ts.map +1 -0
  123. package/dist/db/widen-columns.js +73 -0
  124. package/dist/db/widen-columns.js.map +1 -0
  125. package/dist/mcp/build-server.d.ts.map +1 -1
  126. package/dist/mcp/build-server.js +1 -0
  127. package/dist/mcp/build-server.js.map +1 -1
  128. package/dist/oauth-tokens/store.d.ts.map +1 -1
  129. package/dist/oauth-tokens/store.js +6 -0
  130. package/dist/oauth-tokens/store.js.map +1 -1
  131. package/dist/provider-api/custom-registry.d.ts.map +1 -1
  132. package/dist/provider-api/custom-registry.js +8 -0
  133. package/dist/provider-api/custom-registry.js.map +1 -1
  134. package/dist/resources/store.d.ts.map +1 -1
  135. package/dist/resources/store.js +9 -0
  136. package/dist/resources/store.js.map +1 -1
  137. package/dist/scripts/runner.js +4 -3
  138. package/dist/scripts/runner.js.map +1 -1
  139. package/dist/server/action-discovery.d.ts.map +1 -1
  140. package/dist/server/action-discovery.js +6 -0
  141. package/dist/server/action-discovery.js.map +1 -1
  142. package/dist/server/action-routes.d.ts.map +1 -1
  143. package/dist/server/action-routes.js +1 -0
  144. package/dist/server/action-routes.js.map +1 -1
  145. package/dist/server/auth.d.ts.map +1 -1
  146. package/dist/server/auth.js +5 -0
  147. package/dist/server/auth.js.map +1 -1
  148. package/dist/server/core-routes-plugin.d.ts.map +1 -1
  149. package/dist/server/core-routes-plugin.js +13 -0
  150. package/dist/server/core-routes-plugin.js.map +1 -1
  151. package/dist/server/security-headers.d.ts +8 -5
  152. package/dist/server/security-headers.d.ts.map +1 -1
  153. package/dist/server/security-headers.js +9 -6
  154. package/dist/server/security-headers.js.map +1 -1
  155. package/dist/settings/store.d.ts.map +1 -1
  156. package/dist/settings/store.js +6 -0
  157. package/dist/settings/store.js.map +1 -1
  158. package/dist/templates/workspace-core/.agents/skills/audit-log/SKILL.md +93 -0
  159. package/dist/usage/store.d.ts.map +1 -1
  160. package/dist/usage/store.js +5 -0
  161. package/dist/usage/store.js.map +1 -1
  162. package/docs/content/actions.md +23 -0
  163. package/docs/content/audit-log.md +111 -0
  164. package/package.json +2 -1
  165. package/src/templates/workspace-core/.agents/skills/audit-log/SKILL.md +93 -0
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Pure (no-DB) audit configuration helpers.
3
+ *
4
+ * Kept free of any database / store import so `action.ts` can statically
5
+ * import them without pulling the DB client into every bundle that touches an
6
+ * action. The DB-touching recorder lives in `record.ts`, which `action.ts`
7
+ * loads lazily via dynamic import on first audited call.
8
+ */
9
+ import type {
10
+ ActionAuditConfig,
11
+ AuditActorKind,
12
+ AuditStatus,
13
+ } from "./types.js";
14
+
15
+ /**
16
+ * High-frequency / ephemeral framework actions that are not meaningful audit
17
+ * events. They mutate UI/agent-context state many times per session; auditing
18
+ * each one would flood the log without recording a real user-facing change.
19
+ *
20
+ * An action can still force itself on with `audit: { enabled: true }` —
21
+ * explicit config always wins over this denylist (see `shouldRecordAudit`).
22
+ */
23
+ const DEFAULT_SKIP_ACTIONS = new Set<string>([
24
+ "context-pin",
25
+ "context-evict",
26
+ "context-restore",
27
+ "context-report",
28
+ "context-manifest-get",
29
+ "change-appearance",
30
+ "toggle-demo-mode",
31
+ ]);
32
+
33
+ /** Name patterns for high-frequency state-sync actions, skipped by default. */
34
+ const DEFAULT_SKIP_PATTERN =
35
+ /(application-state|app-state|set-state|view-screen|navigate|poll)/i;
36
+
37
+ /** Normalize a raw `audit` option into a config object (or undefined). */
38
+ export function normalizeAuditConfig(
39
+ raw: unknown,
40
+ ): ActionAuditConfig | undefined {
41
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
42
+ return raw as ActionAuditConfig;
43
+ }
44
+
45
+ /**
46
+ * Whether to attach the audit wrapper to an action at definition time. Decided
47
+ * from the action's resolved `readOnly` flag plus its config — the action's
48
+ * *name* isn't known here (it's the registry key), so name-based skipping
49
+ * happens later in `shouldRecordAudit`.
50
+ */
51
+ export function resolveAuditAttach(
52
+ config: ActionAuditConfig | undefined,
53
+ readOnly: boolean | undefined,
54
+ ): boolean {
55
+ if (config && typeof config.enabled === "boolean") return config.enabled;
56
+ // Read-only actions are not audited unless they opt in via `onRead`.
57
+ if (readOnly === true) return config?.onRead === true;
58
+ // Everything else mutates — audit by default.
59
+ return true;
60
+ }
61
+
62
+ /**
63
+ * Final, name-aware decision made at record time. Explicit `enabled: true`
64
+ * overrides the high-frequency denylist; otherwise denylisted names are
65
+ * dropped.
66
+ */
67
+ export function shouldRecordAudit(
68
+ config: ActionAuditConfig | undefined,
69
+ actionName: string,
70
+ ): boolean {
71
+ if (config && config.enabled === true) return true;
72
+ if (DEFAULT_SKIP_ACTIONS.has(actionName)) return false;
73
+ if (DEFAULT_SKIP_PATTERN.test(actionName)) return false;
74
+ return true;
75
+ }
76
+
77
+ /** Derive the actor kind from the invocation surface + resolved identity. */
78
+ export function deriveActorKind(
79
+ caller: string | undefined,
80
+ actorEmail: string | undefined | null,
81
+ ): AuditActorKind {
82
+ if (caller === "tool") return "agent";
83
+ return actorEmail ? "human" : "system";
84
+ }
85
+
86
+ /** Whether the whole subsystem is disabled via env. */
87
+ export function isAuditDisabled(): boolean {
88
+ return process.env.AGENT_NATIVE_AUDIT_ENABLED === "false";
89
+ }
90
+
91
+ export type { AuditStatus };
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Framework audit log — a durable, complete, access-scoped, append-only record
3
+ * of who mutated what app data, when, from where, and (for the agent) in which
4
+ * run. Distinct from observability (sampled telemetry) and tracking
5
+ * (fire-and-forget analytics). Capture is automatic at the `defineAction` seam.
6
+ */
7
+ export type {
8
+ ActionAuditConfig,
9
+ AuditActorKind,
10
+ AuditCallMeta,
11
+ AuditEvent,
12
+ AuditQueryFilters,
13
+ AuditStatus,
14
+ AuditTarget,
15
+ AuditVisibility,
16
+ } from "./types.js";
17
+
18
+ export {
19
+ deriveActorKind,
20
+ isAuditDisabled,
21
+ normalizeAuditConfig,
22
+ resolveAuditAttach,
23
+ shouldRecordAudit,
24
+ } from "./config.js";
25
+
26
+ export { redactArgsToJson } from "./redact.js";
27
+
28
+ export {
29
+ ensureAuditTables,
30
+ insertAuditEvent,
31
+ queryAuditEvents,
32
+ getAuditEventById,
33
+ deleteOldAuditEvents,
34
+ type AuditReadScope,
35
+ } from "./store.js";
36
+
37
+ export { recordActionAudit } from "./record.js";
38
+
39
+ export {
40
+ runAuditCleanupOnce,
41
+ startAuditCleanupJob,
42
+ stopAuditCleanupJob,
43
+ } from "./cleanup-job.js";
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Audit capture entry point, called from the `defineAction` audit wrapper after
3
+ * an action runs (success or error). Best-effort: any failure here is swallowed
4
+ * so auditing never breaks the action it observes.
5
+ *
6
+ * This module touches the DB (`store.js`), so `action.ts` loads it lazily via
7
+ * dynamic import on the first audited call — keeping the DB client out of every
8
+ * bundle that merely defines actions.
9
+ */
10
+ import {
11
+ deriveActorKind,
12
+ isAuditDisabled,
13
+ shouldRecordAudit,
14
+ } from "./config.js";
15
+ import { redactArgsToJson } from "./redact.js";
16
+ import { insertAuditEvent } from "./store.js";
17
+ import type {
18
+ ActionAuditConfig,
19
+ AuditCallMeta,
20
+ AuditEvent,
21
+ AuditStatus,
22
+ AuditTarget,
23
+ } from "./types.js";
24
+
25
+ /** Minimal view of the action run context the recorder needs. */
26
+ export interface AuditRunContextLike {
27
+ actionName?: string;
28
+ caller?: string;
29
+ userEmail?: string;
30
+ orgId?: string | null;
31
+ threadId?: string;
32
+ turnId?: string;
33
+ }
34
+
35
+ export interface RecordActionAuditInput {
36
+ config: ActionAuditConfig | undefined;
37
+ args: unknown;
38
+ ctx: AuditRunContextLike | undefined;
39
+ status: AuditStatus;
40
+ result?: unknown;
41
+ error?: unknown;
42
+ }
43
+
44
+ function errorCode(error: unknown): string | null {
45
+ if (!error) return null;
46
+ if (typeof error === "object") {
47
+ const e = error as { errorCode?: unknown; code?: unknown; name?: unknown };
48
+ if (typeof e.errorCode === "string") return e.errorCode;
49
+ if (typeof e.code === "string") return e.code;
50
+ if (typeof e.name === "string") return e.name;
51
+ }
52
+ return "error";
53
+ }
54
+
55
+ function safeTarget(
56
+ config: ActionAuditConfig | undefined,
57
+ args: unknown,
58
+ result: unknown,
59
+ meta: AuditCallMeta,
60
+ ): AuditTarget | null {
61
+ if (!config?.target) return null;
62
+ try {
63
+ return config.target(args, result, meta) ?? null;
64
+ } catch {
65
+ return null;
66
+ }
67
+ }
68
+
69
+ function safeSummary(
70
+ config: ActionAuditConfig | undefined,
71
+ args: unknown,
72
+ result: unknown,
73
+ meta: AuditCallMeta,
74
+ ): string | null {
75
+ if (!config?.summary) return null;
76
+ try {
77
+ const s = config.summary(args, result, meta);
78
+ return typeof s === "string" ? s.slice(0, 500) : null;
79
+ } catch {
80
+ return null;
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Record one audit event. Resolves the actor, target, ownership (for scoped
86
+ * reads), and redacted inputs, then appends a row. Never throws.
87
+ */
88
+ export async function recordActionAudit(
89
+ input: RecordActionAuditInput,
90
+ ): Promise<void> {
91
+ try {
92
+ if (isAuditDisabled()) return;
93
+ const ctx = input.ctx;
94
+ const actionName = ctx?.actionName;
95
+ // No name → an internal/programmatic run() with no dispatch context. Skip
96
+ // rather than write a nameless row.
97
+ if (!actionName) return;
98
+ if (!shouldRecordAudit(input.config, actionName)) return;
99
+
100
+ const caller = ctx?.caller ?? "http";
101
+ const actorEmail = ctx?.userEmail ?? null;
102
+ const meta: AuditCallMeta = {
103
+ status: input.status,
104
+ caller,
105
+ userEmail: ctx?.userEmail,
106
+ orgId: ctx?.orgId ?? null,
107
+ };
108
+
109
+ const target = safeTarget(input.config, input.args, input.result, meta);
110
+ const summary = safeSummary(input.config, input.args, input.result, meta);
111
+
112
+ const recordInputs = input.config?.recordInputs !== false;
113
+ const inputJson = recordInputs ? redactArgsToJson(input.args) : null;
114
+
115
+ const event: AuditEvent = {
116
+ id: crypto.randomUUID(),
117
+ createdAt: Date.now(),
118
+ action: actionName,
119
+ caller,
120
+ actorKind: deriveActorKind(caller, actorEmail),
121
+ actorEmail,
122
+ orgId: ctx?.orgId ?? null,
123
+ threadId: ctx?.threadId ?? null,
124
+ turnId: ctx?.turnId ?? null,
125
+ targetType: target?.type ?? null,
126
+ targetId: target?.id ?? null,
127
+ status: input.status,
128
+ summary,
129
+ input: inputJson,
130
+ errorCode: input.status === "error" ? errorCode(input.error) : null,
131
+ // Scope reads to the resource owner when the action declares one,
132
+ // otherwise to the actor (the common self-mutation case).
133
+ ownerEmail: target?.ownerEmail ?? actorEmail,
134
+ visibility: target?.visibility ?? "private",
135
+ };
136
+ // org_id used for scoping defaults to the target's, else the actor's org.
137
+ if (target?.orgId !== undefined) event.orgId = target.orgId;
138
+
139
+ await insertAuditEvent(event);
140
+ } catch {
141
+ // Best-effort — auditing must never break the audited action.
142
+ }
143
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Redaction for audit-captured arguments.
3
+ *
4
+ * The audit log must never become a secondary store of secrets. Before any
5
+ * call arguments are persisted we:
6
+ * - drop values under credential-looking keys (token, secret, password, …),
7
+ * - redact string values that look like bearer tokens / long opaque keys,
8
+ * - truncate oversized strings and cap the serialized payload size.
9
+ *
10
+ * This mirrors the framework's standing rule that credential-looking literals
11
+ * never land in source, logs, or fixtures.
12
+ */
13
+
14
+ const SENSITIVE_KEY =
15
+ /(pass(word|phrase)?|secret|token|api[_-]?key|apikey|authorization|bearer|credential|cookie|session[_-]?(id|token)|private[_-]?key|client[_-]?secret|signing[_-]?secret|access[_-]?key|refresh[_-]?token|webhook[_-]?(url|secret))/i;
16
+
17
+ const REDACTED = "[redacted]";
18
+ const MAX_STRING = 2000;
19
+ const MAX_DEPTH = 6;
20
+ const MAX_KEYS = 100;
21
+ const MAX_ARRAY = 100;
22
+ const MAX_JSON = 8000;
23
+
24
+ /** Heuristic: does a bare string value look like a secret? */
25
+ function looksSecret(value: string): boolean {
26
+ if (/^bearer\s+\S/i.test(value)) return true;
27
+ // Long, unbroken, high-entropy-ish opaque token (hex/base64url, no spaces).
28
+ if (value.length >= 32 && /^[A-Za-z0-9_\-+/=.]+$/.test(value)) return true;
29
+ // Common secret prefixes (Stripe, GitHub, OpenAI, Slack, AWS, …).
30
+ if (/^(sk|pk|rk|ghp|gho|xox[baprs]|AKIA|AIza|ya29)[-_]/i.test(value)) {
31
+ return true;
32
+ }
33
+ // Webhook URLs carry their secret in the path — redact regardless of the key
34
+ // they arrive under (e.g. a generic `value` field holding a Slack webhook).
35
+ if (
36
+ /^https?:\/\/(hooks\.slack\.com\/|[^/]*\.webhook\.office\.com\/|(canary\.|ptb\.)?discord(app)?\.com\/api\/webhooks\/|hooks\.zapier\.com\/|maker\.ifttt\.com\/|discord\.com\/api\/webhooks\/)/i.test(
37
+ value,
38
+ )
39
+ ) {
40
+ return true;
41
+ }
42
+ return false;
43
+ }
44
+
45
+ function redactString(value: string): string {
46
+ if (looksSecret(value)) return REDACTED;
47
+ if (value.length > MAX_STRING) {
48
+ return `${value.slice(0, MAX_STRING)}…(${value.length - MAX_STRING} more chars)`;
49
+ }
50
+ return value;
51
+ }
52
+
53
+ function redact(value: unknown, depth: number): unknown {
54
+ if (value == null) return value;
55
+ if (typeof value === "string") return redactString(value);
56
+ if (typeof value === "number" || typeof value === "boolean") return value;
57
+ if (depth >= MAX_DEPTH) return "[…]";
58
+ if (Array.isArray(value)) {
59
+ const out = value.slice(0, MAX_ARRAY).map((v) => redact(v, depth + 1));
60
+ if (value.length > MAX_ARRAY)
61
+ out.push(`…(${value.length - MAX_ARRAY} more)`);
62
+ return out;
63
+ }
64
+ if (typeof value === "object") {
65
+ const out: Record<string, unknown> = {};
66
+ let n = 0;
67
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
68
+ if (n >= MAX_KEYS) {
69
+ out["…"] = "(truncated)";
70
+ break;
71
+ }
72
+ n += 1;
73
+ out[k] = SENSITIVE_KEY.test(k) ? REDACTED : redact(v, depth + 1);
74
+ }
75
+ return out;
76
+ }
77
+ // Functions, symbols, bigint, etc. — not serializable / not interesting.
78
+ return undefined;
79
+ }
80
+
81
+ /**
82
+ * Redact and serialize call arguments to a capped JSON string, or `null` when
83
+ * there is nothing to record. Never throws.
84
+ */
85
+ export function redactArgsToJson(args: unknown): string | null {
86
+ try {
87
+ if (args == null) return null;
88
+ const redacted = redact(args, 0);
89
+ if (redacted === undefined) return null;
90
+ const json = JSON.stringify(redacted);
91
+ if (json == null) return null;
92
+ if (json.length > MAX_JSON) {
93
+ // Slicing the serialized JSON would yield an unparseable string. Wrap a
94
+ // preview in a valid envelope so `get-audit-event` can always JSON.parse
95
+ // the stored `input`.
96
+ return JSON.stringify({
97
+ _auditTruncated: true,
98
+ originalBytes: json.length,
99
+ preview: json.slice(0, MAX_JSON),
100
+ });
101
+ }
102
+ return json;
103
+ } catch {
104
+ return null;
105
+ }
106
+ }
107
+
108
+ /** Exposed for tests. */
109
+ export const __test = { looksSecret, redact, SENSITIVE_KEY };
@@ -0,0 +1,244 @@
1
+ /**
2
+ * SQL persistence for the framework audit log.
3
+ *
4
+ * Follows the same raw-SQL, provider-agnostic pattern as observability/store.ts
5
+ * and usage/store.ts — framework tables use `getDbExec()` + `intType()` rather
6
+ * than Drizzle ORM (which is for template-level schemas). One append-only table
7
+ * `agent_audit_log`; reads are scoped to the caller's identity in SQL (no
8
+ * shares table — audit rows are never individually shared).
9
+ */
10
+ import { getDbExec, intType, retryOnDdlRace } from "../db/client.js";
11
+ import type {
12
+ AuditEvent,
13
+ AuditQueryFilters,
14
+ AuditVisibility,
15
+ } from "./types.js";
16
+
17
+ let _initPromise: Promise<void> | undefined;
18
+
19
+ export async function ensureAuditTables(): Promise<void> {
20
+ if (!_initPromise) {
21
+ _initPromise = (async () => {
22
+ const client = getDbExec();
23
+
24
+ await retryOnDdlRace(() =>
25
+ client.execute(`
26
+ CREATE TABLE IF NOT EXISTS agent_audit_log (
27
+ id TEXT PRIMARY KEY,
28
+ created_at ${intType()} NOT NULL,
29
+ action TEXT NOT NULL,
30
+ caller TEXT NOT NULL,
31
+ actor_kind TEXT NOT NULL,
32
+ actor_email TEXT,
33
+ org_id TEXT,
34
+ thread_id TEXT,
35
+ turn_id TEXT,
36
+ target_type TEXT,
37
+ target_id TEXT,
38
+ status TEXT NOT NULL DEFAULT 'success',
39
+ summary TEXT,
40
+ input TEXT,
41
+ error_code TEXT,
42
+ owner_email TEXT,
43
+ visibility TEXT NOT NULL DEFAULT 'private'
44
+ )
45
+ `),
46
+ );
47
+
48
+ const indexes = [
49
+ `CREATE INDEX IF NOT EXISTS idx_audit_owner ON agent_audit_log (owner_email, created_at)`,
50
+ `CREATE INDEX IF NOT EXISTS idx_audit_org ON agent_audit_log (org_id, created_at)`,
51
+ `CREATE INDEX IF NOT EXISTS idx_audit_target ON agent_audit_log (target_type, target_id, created_at)`,
52
+ `CREATE INDEX IF NOT EXISTS idx_audit_turn ON agent_audit_log (turn_id)`,
53
+ `CREATE INDEX IF NOT EXISTS idx_audit_actor ON agent_audit_log (actor_email, created_at)`,
54
+ `CREATE INDEX IF NOT EXISTS idx_audit_created ON agent_audit_log (created_at)`,
55
+ ];
56
+ for (const sql of indexes) {
57
+ try {
58
+ await client.execute(sql);
59
+ } catch {
60
+ // Index creation is best-effort; a racing boot may have created it.
61
+ }
62
+ }
63
+ })().catch((err) => {
64
+ // Allow a later call to retry if the first init failed.
65
+ _initPromise = undefined;
66
+ throw err;
67
+ });
68
+ }
69
+ return _initPromise;
70
+ }
71
+
72
+ export async function insertAuditEvent(event: AuditEvent): Promise<void> {
73
+ await ensureAuditTables();
74
+ const client = getDbExec();
75
+ await client.execute({
76
+ sql: `INSERT INTO agent_audit_log
77
+ (id, created_at, action, caller, actor_kind, actor_email, org_id,
78
+ thread_id, turn_id, target_type, target_id, status, summary, input,
79
+ error_code, owner_email, visibility)
80
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
81
+ args: [
82
+ event.id,
83
+ event.createdAt,
84
+ event.action,
85
+ event.caller,
86
+ event.actorKind,
87
+ event.actorEmail,
88
+ event.orgId,
89
+ event.threadId,
90
+ event.turnId,
91
+ event.targetType,
92
+ event.targetId,
93
+ event.status,
94
+ event.summary,
95
+ event.input,
96
+ event.errorCode,
97
+ event.ownerEmail,
98
+ event.visibility,
99
+ ],
100
+ });
101
+ }
102
+
103
+ function mapRow(row: any): AuditEvent {
104
+ return {
105
+ id: String(row.id),
106
+ createdAt: Number(row.created_at),
107
+ action: String(row.action),
108
+ caller: String(row.caller),
109
+ actorKind: row.actor_kind,
110
+ actorEmail: row.actor_email ?? null,
111
+ orgId: row.org_id ?? null,
112
+ threadId: row.thread_id ?? null,
113
+ turnId: row.turn_id ?? null,
114
+ targetType: row.target_type ?? null,
115
+ targetId: row.target_id ?? null,
116
+ status: row.status,
117
+ summary: row.summary ?? null,
118
+ input: row.input ?? null,
119
+ errorCode: row.error_code ?? null,
120
+ ownerEmail: row.owner_email ?? null,
121
+ visibility: (row.visibility ?? "private") as AuditVisibility,
122
+ };
123
+ }
124
+
125
+ export interface AuditReadScope {
126
+ userEmail?: string;
127
+ orgId?: string | null;
128
+ }
129
+
130
+ /**
131
+ * Build the access-scoping WHERE fragment + args. A caller sees audit rows they
132
+ * own, plus org-visible rows in their org. With no identity, nothing matches —
133
+ * the audit log never leaks cross-tenant. Mirrors the core ownership clause of
134
+ * `accessFilter` (minus shares, which audit rows don't have).
135
+ */
136
+ function scopeClause(scope: AuditReadScope): { sql: string; args: any[] } {
137
+ const clauses: string[] = [];
138
+ const args: any[] = [];
139
+ if (scope.userEmail) {
140
+ if (scope.orgId) {
141
+ // Constrain the owner's rows to the active org — plus legacy/solo rows
142
+ // that predate org-scoping (org_id IS NULL) — mirroring sharing's
143
+ // `ownerScopeFilter`, so switching orgs doesn't surface another org's
144
+ // trail.
145
+ clauses.push("(owner_email = ? AND (org_id = ? OR org_id IS NULL))");
146
+ args.push(scope.userEmail, scope.orgId);
147
+ } else {
148
+ clauses.push("owner_email = ?");
149
+ args.push(scope.userEmail);
150
+ }
151
+ }
152
+ if (scope.orgId) {
153
+ clauses.push("(visibility = 'org' AND org_id = ?)");
154
+ args.push(scope.orgId);
155
+ }
156
+ if (clauses.length === 0) return { sql: "1=0", args };
157
+ return { sql: `(${clauses.join(" OR ")})`, args };
158
+ }
159
+
160
+ const MAX_LIMIT = 500;
161
+ const DEFAULT_LIMIT = 100;
162
+
163
+ // Columns returned by the list surface — deliberately EXCLUDES `input` so a
164
+ // timeline query never streams every event's (redacted) request body in bulk.
165
+ // Fetch the full payload one event at a time via `getAuditEventById`.
166
+ const LIST_COLUMNS =
167
+ "id, created_at, action, caller, actor_kind, actor_email, org_id, " +
168
+ "thread_id, turn_id, target_type, target_id, status, summary, " +
169
+ "error_code, owner_email, visibility";
170
+
171
+ export async function queryAuditEvents(
172
+ scope: AuditReadScope,
173
+ filters: AuditQueryFilters = {},
174
+ ): Promise<AuditEvent[]> {
175
+ await ensureAuditTables();
176
+ if (!scope.userEmail && !scope.orgId) return [];
177
+ const client = getDbExec();
178
+
179
+ const scoped = scopeClause(scope);
180
+ const where: string[] = [scoped.sql];
181
+ const args: any[] = [...scoped.args];
182
+
183
+ const push = (clause: string, value: any) => {
184
+ where.push(clause);
185
+ args.push(value);
186
+ };
187
+ if (filters.targetType) push("target_type = ?", filters.targetType);
188
+ if (filters.targetId) push("target_id = ?", filters.targetId);
189
+ if (filters.actorKind) push("actor_kind = ?", filters.actorKind);
190
+ if (filters.actorEmail) push("actor_email = ?", filters.actorEmail);
191
+ if (filters.status) push("status = ?", filters.status);
192
+ if (filters.threadId) push("thread_id = ?", filters.threadId);
193
+ if (filters.turnId) push("turn_id = ?", filters.turnId);
194
+ if (filters.action) push("action = ?", filters.action);
195
+ if (typeof filters.sinceMs === "number") {
196
+ push("created_at >= ?", Math.floor(filters.sinceMs));
197
+ }
198
+
199
+ const limit = Math.min(
200
+ Math.max(1, Math.floor(filters.limit ?? DEFAULT_LIMIT)),
201
+ MAX_LIMIT,
202
+ );
203
+
204
+ const result = await client.execute({
205
+ sql: `SELECT ${LIST_COLUMNS} FROM agent_audit_log
206
+ WHERE ${where.join(" AND ")}
207
+ ORDER BY created_at DESC
208
+ LIMIT ?`,
209
+ args: [...args, limit],
210
+ });
211
+ return (result.rows ?? []).map(mapRow);
212
+ }
213
+
214
+ export async function getAuditEventById(
215
+ id: string,
216
+ scope: AuditReadScope,
217
+ ): Promise<AuditEvent | null> {
218
+ await ensureAuditTables();
219
+ if (!scope.userEmail && !scope.orgId) return null;
220
+ const client = getDbExec();
221
+ const scoped = scopeClause(scope);
222
+ const result = await client.execute({
223
+ sql: `SELECT * FROM agent_audit_log WHERE id = ? AND ${scoped.sql} LIMIT 1`,
224
+ args: [id, ...scoped.args],
225
+ });
226
+ const row = (result.rows ?? [])[0];
227
+ return row ? mapRow(row) : null;
228
+ }
229
+
230
+ /** Purge audit rows older than `cutoffMs`. Returns the deleted row count. */
231
+ export async function deleteOldAuditEvents(cutoffMs: number): Promise<number> {
232
+ await ensureAuditTables();
233
+ const client = getDbExec();
234
+ const result = await client.execute({
235
+ sql: `DELETE FROM agent_audit_log WHERE created_at < ?`,
236
+ args: [Math.floor(cutoffMs)],
237
+ });
238
+ return Number(result.rowsAffected ?? 0);
239
+ }
240
+
241
+ /** Test-only: reset the cached init promise so a fresh DB re-creates tables. */
242
+ export function __resetAuditInitForTests(): void {
243
+ _initPromise = undefined;
244
+ }