@alfe.ai/openclaw-identity 0.0.10 → 0.0.11

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.
package/dist/index.cjs CHANGED
@@ -1,2 +1,27 @@
1
- const require_plugin = require("./plugin2.cjs");
2
- module.exports = require_plugin.plugin;
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ const require_plugin = require("./plugin.cjs");
6
+ //#region src/runtime-contract.ts
7
+ /**
8
+ * Build the gate context object used by sift evaluation. This is the
9
+ * round-6 "strict namespacing" shape — `args` is a top-level field, not
10
+ * spread, so an attacker-controlled `tool` field inside `toolArgs` cannot
11
+ * override the gate's `tool` value.
12
+ *
13
+ * Stage E's gate calls:
14
+ * ability.has(
15
+ * { subject: "agent", action: "exec", scope: `agent:${ctx.agentId}` },
16
+ * buildGateContext(event),
17
+ * );
18
+ */
19
+ function buildGateContext(event) {
20
+ return {
21
+ tool: event.toolName,
22
+ args: event.toolArgs
23
+ };
24
+ }
25
+ //#endregion
26
+ exports.buildGateContext = buildGateContext;
27
+ exports.default = require_plugin;
package/dist/index.d.cts CHANGED
@@ -1,2 +1,147 @@
1
1
  import plugin from "./plugin.cjs";
2
- export { plugin as default };
2
+
3
+ //#region src/policy-cache.d.ts
4
+
5
+ type IdentityFailureMode = "open" | "closed" | "permissive";
6
+ /**
7
+ * Evaluate whether a tool call should be blocked based on the cached policy
8
+ * and failure mode.
9
+ */
10
+
11
+ //#endregion
12
+ //#region src/runtime-contract.d.ts
13
+
14
+ /**
15
+ * The tool the agent is about to call.
16
+ *
17
+ * `toolName` SHOULD be namespaced (e.g., `gmail:send_email`, `calendar:create_event`)
18
+ * so sift `$glob: "gmail:*"` conditions work and namespace collisions are
19
+ * impossible. Plugins that don't yet namespace their tools will be migrated
20
+ * during Stage I rollout.
21
+ */
22
+ interface ToolCallEvent {
23
+ /** Namespaced tool name, e.g. "gmail:send_email". */
24
+ readonly toolName: string;
25
+ /** Arbitrary argument bag passed to the tool's `execute` function. */
26
+ readonly toolArgs: Record<string, unknown>;
27
+ }
28
+ /**
29
+ * What initiated the tool call. Three buckets:
30
+ * - "user_message" — a human (or another agent) sent a message that the
31
+ * agent is now responding to. `actingIdentityId` is the
32
+ * identity of the message sender.
33
+ * - "scheduled" — autonomous run (cron/trigger). `actingIdentityId` is
34
+ * the agent's own identity (`idn_agt_*`).
35
+ * - "tool_chain" — a follow-up tool call from a previous tool's result
36
+ * within the same agent invocation. `actingIdentityId`
37
+ * is whatever resolved at the start of the chain.
38
+ * - "api" — a tool call invoked via the agent's REST API by an
39
+ * external caller authenticated with an `alfe_*` token.
40
+ * `actingIdentityId` may be undefined; `tokenPermissions`
41
+ * carries the gate-relevant `Permission[]`.
42
+ */
43
+ type ToolCallTrigger = "user_message" | "scheduled" | "tool_chain" | "api";
44
+ /**
45
+ * How the caller authenticated.
46
+ * - "jwt" — Clerk JWT path (human user). `actingIdentityId` resolved from
47
+ * the JWT's `sub` via the identity service.
48
+ * - "agent" — autonomous agent (no external caller). `actingIdentityId` is
49
+ * the agent's own `idn_agt_*`.
50
+ * - "token" — `alfe_*` API token. `tokenPermissions` is set; the gate uses
51
+ * the token's permissions directly without an identity lookup.
52
+ * - "none" — no auth context (fail-closed in prod via IdentityFailureMode).
53
+ */
54
+ type ToolCallAuthMethod = "jwt" | "agent" | "token" | "none";
55
+ /**
56
+ * Permission shape the gate consumes. This is a structural duplicate of
57
+ * `Permission` from `@auriclabs/roles@0.1.1` so the openclaw plugin doesn't
58
+ * have to depend on the library directly (the library is consumed inside the
59
+ * gate itself in Stage E). Keep the two shapes in lockstep.
60
+ */
61
+ interface RuntimePermission {
62
+ readonly subject: string;
63
+ readonly action: string;
64
+ readonly scope?: string;
65
+ /**
66
+ * Round 7 storage shape: sift conditions stored per-permission. The runtime
67
+ * gate evaluates the condition against `{ tool, args }` (round 6 strict
68
+ * namespacing). Glob source travels under `$glob`; the compiled regex
69
+ * travels under `_glob_re` with a `_glob_v` version marker (round 7 audit
70
+ * 3.6 storage shape).
71
+ */
72
+ readonly conditions?: Record<string, unknown>;
73
+ readonly type?: "can" | "cannot";
74
+ }
75
+ /**
76
+ * Calling context for the tool call. Populated by the OpenClaw daemon at
77
+ * dispatch time.
78
+ */
79
+ interface ToolCallContext {
80
+ /** Required: the tenant (`org_*`) that owns the agent. */
81
+ readonly tenantId: string;
82
+ /** Required: the agent (`agt_*`) that is about to call the tool. */
83
+ readonly agentId: string;
84
+ /** Required: how the caller authenticated. */
85
+ readonly authMethod: ToolCallAuthMethod;
86
+ /** Required: what initiated the call. */
87
+ readonly trigger: ToolCallTrigger;
88
+ /**
89
+ * The identity (`idn_*`) the agent is acting on behalf of. Resolution
90
+ * order:
91
+ * 1. If `trigger === "user_message"`: the chat-context identity (sender).
92
+ * 2. If `trigger === "scheduled"` or `trigger === "tool_chain"`: the
93
+ * agent's own `idn_agt_*` (autonomous default).
94
+ * 3. If `authMethod === "token"`: optional; the token-path gate uses
95
+ * `tokenPermissions` and may skip identity resolution entirely.
96
+ * 4. Otherwise: undefined; the per-agent `IdentityFailureMode` decides
97
+ * whether to allow / deny / log-and-continue.
98
+ */
99
+ readonly actingIdentityId?: string;
100
+ /**
101
+ * Round 5 / Round 7: `alfe_*` tokens carry their own flat `Permission[]`
102
+ * directly. When `authMethod === "token"`, the daemon populates this with
103
+ * `TokenEntity.permissions` (post Stage B.0.7 atomic flip — pre-flip the
104
+ * authorizer derives this from `record.scopes` via `scopesToPermissions`).
105
+ * The Stage E gate evaluates these permissions directly at scope
106
+ * `agent:<agentId>` without an identity lookup.
107
+ */
108
+ readonly tokenPermissions?: readonly RuntimePermission[];
109
+ /** Optional: chat conversation id (when trigger is `user_message`). */
110
+ readonly conversationId?: string;
111
+ /** Optional: channel id (when trigger is `user_message`). */
112
+ readonly channelId?: string;
113
+ }
114
+ /**
115
+ * Return value of the `before_tool_call` hook.
116
+ * - `undefined` — allow.
117
+ * - `{ block: true, blockReason: string }` — deny with reason surfaced to
118
+ * the agent's response (Stage E behaviour).
119
+ */
120
+ type ToolCallHookResult = undefined | {
121
+ block: true;
122
+ blockReason: string;
123
+ };
124
+ /**
125
+ * Strongly-typed `before_tool_call` hook signature. The plugin's stub uses
126
+ * this signature today; Stage E swaps the stub for the real `agent:exec` +
127
+ * sift gate against `@auriclabs/roles`.
128
+ */
129
+ type BeforeToolCallHook = (event: ToolCallEvent, ctx: ToolCallContext) => Promise<ToolCallHookResult>;
130
+ /**
131
+ * Build the gate context object used by sift evaluation. This is the
132
+ * round-6 "strict namespacing" shape — `args` is a top-level field, not
133
+ * spread, so an attacker-controlled `tool` field inside `toolArgs` cannot
134
+ * override the gate's `tool` value.
135
+ *
136
+ * Stage E's gate calls:
137
+ * ability.has(
138
+ * { subject: "agent", action: "exec", scope: `agent:${ctx.agentId}` },
139
+ * buildGateContext(event),
140
+ * );
141
+ */
142
+ declare function buildGateContext(event: ToolCallEvent): {
143
+ tool: string;
144
+ args: Record<string, unknown>;
145
+ };
146
+ //#endregion
147
+ export { type BeforeToolCallHook, type IdentityFailureMode, type RuntimePermission, type ToolCallAuthMethod, type ToolCallContext, type ToolCallEvent, type ToolCallHookResult, type ToolCallTrigger, buildGateContext, plugin as default };
package/dist/index.d.ts CHANGED
@@ -1,2 +1,147 @@
1
1
  import plugin from "./plugin.js";
2
- export { plugin as default };
2
+
3
+ //#region src/policy-cache.d.ts
4
+
5
+ type IdentityFailureMode = "open" | "closed" | "permissive";
6
+ /**
7
+ * Evaluate whether a tool call should be blocked based on the cached policy
8
+ * and failure mode.
9
+ */
10
+
11
+ //#endregion
12
+ //#region src/runtime-contract.d.ts
13
+
14
+ /**
15
+ * The tool the agent is about to call.
16
+ *
17
+ * `toolName` SHOULD be namespaced (e.g., `gmail:send_email`, `calendar:create_event`)
18
+ * so sift `$glob: "gmail:*"` conditions work and namespace collisions are
19
+ * impossible. Plugins that don't yet namespace their tools will be migrated
20
+ * during Stage I rollout.
21
+ */
22
+ interface ToolCallEvent {
23
+ /** Namespaced tool name, e.g. "gmail:send_email". */
24
+ readonly toolName: string;
25
+ /** Arbitrary argument bag passed to the tool's `execute` function. */
26
+ readonly toolArgs: Record<string, unknown>;
27
+ }
28
+ /**
29
+ * What initiated the tool call. Three buckets:
30
+ * - "user_message" — a human (or another agent) sent a message that the
31
+ * agent is now responding to. `actingIdentityId` is the
32
+ * identity of the message sender.
33
+ * - "scheduled" — autonomous run (cron/trigger). `actingIdentityId` is
34
+ * the agent's own identity (`idn_agt_*`).
35
+ * - "tool_chain" — a follow-up tool call from a previous tool's result
36
+ * within the same agent invocation. `actingIdentityId`
37
+ * is whatever resolved at the start of the chain.
38
+ * - "api" — a tool call invoked via the agent's REST API by an
39
+ * external caller authenticated with an `alfe_*` token.
40
+ * `actingIdentityId` may be undefined; `tokenPermissions`
41
+ * carries the gate-relevant `Permission[]`.
42
+ */
43
+ type ToolCallTrigger = "user_message" | "scheduled" | "tool_chain" | "api";
44
+ /**
45
+ * How the caller authenticated.
46
+ * - "jwt" — Clerk JWT path (human user). `actingIdentityId` resolved from
47
+ * the JWT's `sub` via the identity service.
48
+ * - "agent" — autonomous agent (no external caller). `actingIdentityId` is
49
+ * the agent's own `idn_agt_*`.
50
+ * - "token" — `alfe_*` API token. `tokenPermissions` is set; the gate uses
51
+ * the token's permissions directly without an identity lookup.
52
+ * - "none" — no auth context (fail-closed in prod via IdentityFailureMode).
53
+ */
54
+ type ToolCallAuthMethod = "jwt" | "agent" | "token" | "none";
55
+ /**
56
+ * Permission shape the gate consumes. This is a structural duplicate of
57
+ * `Permission` from `@auriclabs/roles@0.1.1` so the openclaw plugin doesn't
58
+ * have to depend on the library directly (the library is consumed inside the
59
+ * gate itself in Stage E). Keep the two shapes in lockstep.
60
+ */
61
+ interface RuntimePermission {
62
+ readonly subject: string;
63
+ readonly action: string;
64
+ readonly scope?: string;
65
+ /**
66
+ * Round 7 storage shape: sift conditions stored per-permission. The runtime
67
+ * gate evaluates the condition against `{ tool, args }` (round 6 strict
68
+ * namespacing). Glob source travels under `$glob`; the compiled regex
69
+ * travels under `_glob_re` with a `_glob_v` version marker (round 7 audit
70
+ * 3.6 storage shape).
71
+ */
72
+ readonly conditions?: Record<string, unknown>;
73
+ readonly type?: "can" | "cannot";
74
+ }
75
+ /**
76
+ * Calling context for the tool call. Populated by the OpenClaw daemon at
77
+ * dispatch time.
78
+ */
79
+ interface ToolCallContext {
80
+ /** Required: the tenant (`org_*`) that owns the agent. */
81
+ readonly tenantId: string;
82
+ /** Required: the agent (`agt_*`) that is about to call the tool. */
83
+ readonly agentId: string;
84
+ /** Required: how the caller authenticated. */
85
+ readonly authMethod: ToolCallAuthMethod;
86
+ /** Required: what initiated the call. */
87
+ readonly trigger: ToolCallTrigger;
88
+ /**
89
+ * The identity (`idn_*`) the agent is acting on behalf of. Resolution
90
+ * order:
91
+ * 1. If `trigger === "user_message"`: the chat-context identity (sender).
92
+ * 2. If `trigger === "scheduled"` or `trigger === "tool_chain"`: the
93
+ * agent's own `idn_agt_*` (autonomous default).
94
+ * 3. If `authMethod === "token"`: optional; the token-path gate uses
95
+ * `tokenPermissions` and may skip identity resolution entirely.
96
+ * 4. Otherwise: undefined; the per-agent `IdentityFailureMode` decides
97
+ * whether to allow / deny / log-and-continue.
98
+ */
99
+ readonly actingIdentityId?: string;
100
+ /**
101
+ * Round 5 / Round 7: `alfe_*` tokens carry their own flat `Permission[]`
102
+ * directly. When `authMethod === "token"`, the daemon populates this with
103
+ * `TokenEntity.permissions` (post Stage B.0.7 atomic flip — pre-flip the
104
+ * authorizer derives this from `record.scopes` via `scopesToPermissions`).
105
+ * The Stage E gate evaluates these permissions directly at scope
106
+ * `agent:<agentId>` without an identity lookup.
107
+ */
108
+ readonly tokenPermissions?: readonly RuntimePermission[];
109
+ /** Optional: chat conversation id (when trigger is `user_message`). */
110
+ readonly conversationId?: string;
111
+ /** Optional: channel id (when trigger is `user_message`). */
112
+ readonly channelId?: string;
113
+ }
114
+ /**
115
+ * Return value of the `before_tool_call` hook.
116
+ * - `undefined` — allow.
117
+ * - `{ block: true, blockReason: string }` — deny with reason surfaced to
118
+ * the agent's response (Stage E behaviour).
119
+ */
120
+ type ToolCallHookResult = undefined | {
121
+ block: true;
122
+ blockReason: string;
123
+ };
124
+ /**
125
+ * Strongly-typed `before_tool_call` hook signature. The plugin's stub uses
126
+ * this signature today; Stage E swaps the stub for the real `agent:exec` +
127
+ * sift gate against `@auriclabs/roles`.
128
+ */
129
+ type BeforeToolCallHook = (event: ToolCallEvent, ctx: ToolCallContext) => Promise<ToolCallHookResult>;
130
+ /**
131
+ * Build the gate context object used by sift evaluation. This is the
132
+ * round-6 "strict namespacing" shape — `args` is a top-level field, not
133
+ * spread, so an attacker-controlled `tool` field inside `toolArgs` cannot
134
+ * override the gate's `tool` value.
135
+ *
136
+ * Stage E's gate calls:
137
+ * ability.has(
138
+ * { subject: "agent", action: "exec", scope: `agent:${ctx.agentId}` },
139
+ * buildGateContext(event),
140
+ * );
141
+ */
142
+ declare function buildGateContext(event: ToolCallEvent): {
143
+ tool: string;
144
+ args: Record<string, unknown>;
145
+ };
146
+ //#endregion
147
+ export { type BeforeToolCallHook, type IdentityFailureMode, type RuntimePermission, type ToolCallAuthMethod, type ToolCallContext, type ToolCallEvent, type ToolCallHookResult, type ToolCallTrigger, buildGateContext, plugin as default };
package/dist/index.js CHANGED
@@ -1,2 +1,22 @@
1
- import { t as plugin } from "./plugin2.js";
2
- export { plugin as default };
1
+ import plugin from "./plugin.js";
2
+ //#region src/runtime-contract.ts
3
+ /**
4
+ * Build the gate context object used by sift evaluation. This is the
5
+ * round-6 "strict namespacing" shape — `args` is a top-level field, not
6
+ * spread, so an attacker-controlled `tool` field inside `toolArgs` cannot
7
+ * override the gate's `tool` value.
8
+ *
9
+ * Stage E's gate calls:
10
+ * ability.has(
11
+ * { subject: "agent", action: "exec", scope: `agent:${ctx.agentId}` },
12
+ * buildGateContext(event),
13
+ * );
14
+ */
15
+ function buildGateContext(event) {
16
+ return {
17
+ tool: event.toolName,
18
+ args: event.toolArgs
19
+ };
20
+ }
21
+ //#endregion
22
+ export { buildGateContext, plugin as default };
package/dist/plugin.cjs CHANGED
@@ -1,2 +1,325 @@
1
- const require_plugin = require("./plugin2.cjs");
2
- module.exports = require_plugin.plugin;
1
+ let _alfe_ai_config = require("@alfe.ai/config");
2
+ let _alfe_ai_agent_api_client = require("@alfe.ai/agent-api-client");
3
+ let _sinclair_typebox = require("@sinclair/typebox");
4
+ //#region src/plugin.ts
5
+ /**
6
+ * @alfe.ai/openclaw-identity — OpenClaw native plugin
7
+ *
8
+ * HTTP-based identity resolution + AccessConfig admission gate. Installed as
9
+ * part of the core alfe integration on every agent.
10
+ *
11
+ * Hooks:
12
+ * - message_received → always resolves the sender, gates on accessAllowed,
13
+ * blocks unknown senders (read-only resolve).
14
+ * - before_tool_call → typed `(event: ToolCallEvent, ctx: ToolCallContext)`
15
+ * hook (Phase 1 Stage A.0). Today: permissive no-op
16
+ * stub. Phase 1 Stage E swaps the stub for the
17
+ * `agent:exec` + sift gate (Decision 17).
18
+ *
19
+ * `after_tool_call` is intentionally absent — tool-call audit lives in a
20
+ * future dedicated audit service, not in identity.
21
+ */
22
+ const pkg = (0, require("node:module").createRequire)(require("url").pathToFileURL(__filename).href)("../package.json");
23
+ const RESOLVE_CACHE_TTL_MS = 6e4;
24
+ const resolveCache = /* @__PURE__ */ new Map();
25
+ function getCachedResolve(key) {
26
+ const entry = resolveCache.get(key);
27
+ if (!entry) return null;
28
+ if (Date.now() > entry.expiresAt) {
29
+ resolveCache.delete(key);
30
+ return null;
31
+ }
32
+ return entry;
33
+ }
34
+ function setCachedResolve(key, value) {
35
+ resolveCache.set(key, {
36
+ ...value,
37
+ expiresAt: Date.now() + RESOLVE_CACHE_TTL_MS
38
+ });
39
+ }
40
+ function ok(data) {
41
+ return {
42
+ content: [{
43
+ type: "text",
44
+ text: JSON.stringify(data)
45
+ }],
46
+ details: data
47
+ };
48
+ }
49
+ function errResult(message) {
50
+ return {
51
+ content: [{
52
+ type: "text",
53
+ text: JSON.stringify({ error: message })
54
+ }],
55
+ details: { error: message }
56
+ };
57
+ }
58
+ function defineTool(def) {
59
+ return {
60
+ name: def.name,
61
+ description: def.description,
62
+ label: def.name,
63
+ parameters: def.parameters,
64
+ execute: async (_toolCallId, params) => {
65
+ try {
66
+ return ok(await def.handler(params));
67
+ } catch (e) {
68
+ return errResult(e.message);
69
+ }
70
+ }
71
+ };
72
+ }
73
+ const plugin = {
74
+ id: "@alfe.ai/openclaw-identity",
75
+ name: "Alfe Identity",
76
+ description: "Identity resolution and access gating for inbound messages",
77
+ version: pkg.version,
78
+ activate(api) {
79
+ const log = api.logger;
80
+ log.info("Alfe Identity plugin activating...");
81
+ let client;
82
+ try {
83
+ const config = (0, _alfe_ai_config.resolveConfig)();
84
+ client = new _alfe_ai_agent_api_client.AgentApiClient({
85
+ apiKey: config.apiKey,
86
+ apiUrl: config.apiUrl
87
+ });
88
+ } catch (err) {
89
+ log.error(`Identity plugin: failed to resolve config — ${err instanceof Error ? err.message : String(err)}`);
90
+ return;
91
+ }
92
+ const tools = [
93
+ defineTool({
94
+ name: "who_is_this",
95
+ description: "Look up an identity by provider + platformId — returns full identity context (profile, contacts, platforms, notes, tags, recent changelog). Returns `{found:false}` for unknown senders. This tool DOES NOT create new identities.",
96
+ parameters: _sinclair_typebox.Type.Object({
97
+ provider: _sinclair_typebox.Type.String({ description: "Provider name (discord, slack, chat, google-chat, clerk, etc.)" }),
98
+ platformId: _sinclair_typebox.Type.String({ description: "Provider-specific user identifier" })
99
+ }),
100
+ handler: async (params) => {
101
+ const result = await client.resolveIdentity({
102
+ provider: params.provider,
103
+ platformId: params.platformId
104
+ });
105
+ if (!result.identityId) return { found: false };
106
+ return client.getIdentityContext(result.identityId);
107
+ }
108
+ }),
109
+ defineTool({
110
+ name: "lookup_identity",
111
+ description: "Search identities by name. Returns multiple matches.",
112
+ parameters: _sinclair_typebox.Type.Object({
113
+ query: _sinclair_typebox.Type.Optional(_sinclair_typebox.Type.String({ description: "Text search query" })),
114
+ status: _sinclair_typebox.Type.Optional(_sinclair_typebox.Type.String())
115
+ }),
116
+ handler: (params) => client.searchIdentities({
117
+ q: params.query,
118
+ status: params.status
119
+ })
120
+ }),
121
+ defineTool({
122
+ name: "merge_identities",
123
+ description: "Merge two identity records — transfers contacts, platforms, notes, tags, aliases to the survivor. Hard-move, transactional.",
124
+ parameters: _sinclair_typebox.Type.Object({
125
+ survivorId: _sinclair_typebox.Type.String({ description: "Identity to keep" }),
126
+ mergedId: _sinclair_typebox.Type.String({ description: "Identity to merge into survivor" })
127
+ }),
128
+ handler: (params) => client.mergeIdentities(params.survivorId, {
129
+ mergedId: params.mergedId,
130
+ changedBy: {
131
+ type: "agent",
132
+ id: "plugin"
133
+ }
134
+ })
135
+ }),
136
+ defineTool({
137
+ name: "unmerge_identities",
138
+ description: "Reverse a merge — restore previously merged identity.",
139
+ parameters: _sinclair_typebox.Type.Object({ mergedId: _sinclair_typebox.Type.String({ description: "Identity that was merged (has mergedInto pointer)" }) }),
140
+ handler: (params) => client.unmergeIdentity(params.mergedId, { changedBy: {
141
+ type: "agent",
142
+ id: "plugin"
143
+ } })
144
+ }),
145
+ defineTool({
146
+ name: "add_identity_note",
147
+ description: "Add an observation or note about an identity. Use category 'context' for unverified affiliation claims (self-reported title/company) — those do NOT belong on the identity row directly.",
148
+ parameters: _sinclair_typebox.Type.Object({
149
+ identityId: _sinclair_typebox.Type.String(),
150
+ content: _sinclair_typebox.Type.String(),
151
+ category: _sinclair_typebox.Type.Optional(_sinclair_typebox.Type.String({ description: "observation, preference, relationship, context, or warning" }))
152
+ }),
153
+ handler: (params) => client.addIdentityNote(params.identityId, {
154
+ content: params.content,
155
+ category: params.category,
156
+ changedBy: {
157
+ type: "agent",
158
+ id: "plugin"
159
+ }
160
+ })
161
+ }),
162
+ defineTool({
163
+ name: "tag_identity",
164
+ description: "Add or remove a tag on an identity.",
165
+ parameters: _sinclair_typebox.Type.Object({
166
+ identityId: _sinclair_typebox.Type.String(),
167
+ tag: _sinclair_typebox.Type.String(),
168
+ action: _sinclair_typebox.Type.String({ description: "'add' or 'remove'" })
169
+ }),
170
+ handler: (params) => client.tagIdentity(params.identityId, {
171
+ tag: params.tag,
172
+ action: params.action,
173
+ changedBy: {
174
+ type: "agent",
175
+ id: "plugin"
176
+ }
177
+ })
178
+ }),
179
+ defineTool({
180
+ name: "get_identity_changelog",
181
+ description: "Get the changelog for an identity — versions, diffs, who changed what.",
182
+ parameters: _sinclair_typebox.Type.Object({
183
+ identityId: _sinclair_typebox.Type.String(),
184
+ limit: _sinclair_typebox.Type.Optional(_sinclair_typebox.Type.Number())
185
+ }),
186
+ handler: (params) => client.getIdentityChangelog(params.identityId, { limit: params.limit })
187
+ }),
188
+ defineTool({
189
+ name: "rollback_identity",
190
+ description: "Revert an identity to a previous version.",
191
+ parameters: _sinclair_typebox.Type.Object({
192
+ identityId: _sinclair_typebox.Type.String(),
193
+ targetVersion: _sinclair_typebox.Type.Number()
194
+ }),
195
+ handler: (params) => client.rollbackIdentity(params.identityId, {
196
+ targetVersion: params.targetVersion,
197
+ changedBy: {
198
+ type: "agent",
199
+ id: "plugin"
200
+ }
201
+ })
202
+ }),
203
+ defineTool({
204
+ name: "update_identity",
205
+ description: "Update display-shape fields on an identity: name / avatarUrl / timezone / locale. Contact mutations go through the verify flow — this tool will NOT accept email or mobile. Title and company live on org membership rows, not here.",
206
+ parameters: _sinclair_typebox.Type.Object({
207
+ identityId: _sinclair_typebox.Type.String(),
208
+ name: _sinclair_typebox.Type.Optional(_sinclair_typebox.Type.String()),
209
+ avatarUrl: _sinclair_typebox.Type.Optional(_sinclair_typebox.Type.String()),
210
+ timezone: _sinclair_typebox.Type.Optional(_sinclair_typebox.Type.String()),
211
+ locale: _sinclair_typebox.Type.Optional(_sinclair_typebox.Type.String())
212
+ }),
213
+ handler: (params) => {
214
+ const { identityId, ...rest } = params;
215
+ return client.updateIdentity(identityId, rest);
216
+ }
217
+ }),
218
+ defineTool({
219
+ name: "request_identity_verification",
220
+ description: "Send a verification phrase to verify the user controls an email or mobile endpoint. Use this when the user has just told you their email or mobile number and you want them to confirm it. Pass exactly one of `contactEmail` or `contactMobile`. The person must relay the phrase back via `confirm_identity_verification`.",
221
+ parameters: _sinclair_typebox.Type.Object({
222
+ claimedIdentityId: _sinclair_typebox.Type.String({ description: "Identity being claimed" }),
223
+ requestingIdentityId: _sinclair_typebox.Type.String({ description: "Identity of the person making the claim" }),
224
+ requestingProvider: _sinclair_typebox.Type.String({ description: "Provider the requester is on (discord, slack, chat, etc.)" }),
225
+ requestingPlatformId: _sinclair_typebox.Type.String({ description: "Requester's provider-specific user ID" }),
226
+ contactEmail: _sinclair_typebox.Type.Optional(_sinclair_typebox.Type.String({ description: "Email to verify (mutually exclusive with contactMobile)" })),
227
+ contactMobile: _sinclair_typebox.Type.Optional(_sinclair_typebox.Type.String({ description: "E.164 mobile to verify (mutually exclusive with contactEmail)" })),
228
+ preferredChannel: _sinclair_typebox.Type.Optional(_sinclair_typebox.Type.String({ description: "When neither contactEmail nor contactMobile is provided, pick which existing verified contact to deliver to: 'mobile' or 'email'" }))
229
+ }),
230
+ handler: (params) => {
231
+ const contactEmail = params.contactEmail;
232
+ const contactMobile = params.contactMobile;
233
+ if (contactEmail && contactMobile) return Promise.resolve({ error: "Specify exactly one of contactEmail or contactMobile, not both" });
234
+ const contact = contactEmail ? {
235
+ channel: "email",
236
+ value: contactEmail
237
+ } : contactMobile ? {
238
+ channel: "mobile",
239
+ value: contactMobile
240
+ } : void 0;
241
+ return client.requestIdentityVerification({
242
+ claimedIdentityId: params.claimedIdentityId,
243
+ requestingIdentityId: params.requestingIdentityId,
244
+ requestingProvider: params.requestingProvider,
245
+ requestingPlatformId: params.requestingPlatformId,
246
+ preferredChannel: params.preferredChannel,
247
+ contact
248
+ });
249
+ }
250
+ }),
251
+ defineTool({
252
+ name: "confirm_identity_verification",
253
+ description: "Confirm a verification by submitting the phrase the user received. Returns `{ verified, identityId, action }` where `action` is 'merged' (the verified contact already lived on another identity, which is now the survivor) or 'contact_verified' (the contact was attached to the claimed identity).",
254
+ parameters: _sinclair_typebox.Type.Object({
255
+ claimedIdentityId: _sinclair_typebox.Type.String({ description: "Identity being claimed (matches request)" }),
256
+ verificationId: _sinclair_typebox.Type.String({ description: "Verification ID returned from request_identity_verification" }),
257
+ phrase: _sinclair_typebox.Type.String({ description: "Three-word phrase the person received via mobile or email" })
258
+ }),
259
+ handler: (params) => client.confirmIdentityVerification({
260
+ claimedIdentityId: params.claimedIdentityId,
261
+ verificationId: params.verificationId,
262
+ phrase: params.phrase
263
+ })
264
+ })
265
+ ];
266
+ for (const tool of tools) api.registerTool(tool);
267
+ log.info(`Registered ${String(tools.length)} identity tools`);
268
+ api.on("message_received", async (...args) => {
269
+ const event = args[0];
270
+ const ctx = args[1];
271
+ const provider = ctx.channelId ?? "unknown";
272
+ const senderId = event.metadata?.UserId ?? event.from;
273
+ if (!senderId) return;
274
+ const cacheKey = ctx.conversationId ?? `${provider}:${senderId}`;
275
+ const cached = getCachedResolve(cacheKey);
276
+ if (cached) {
277
+ if (cached.identityId == null) return {
278
+ block: true,
279
+ blockReason: "Identity: identity not provisioned for this channel"
280
+ };
281
+ if (!cached.accessAllowed) return {
282
+ block: true,
283
+ blockReason: "Identity: access denied for this sender"
284
+ };
285
+ return;
286
+ }
287
+ try {
288
+ const r = await client.resolveIdentity({
289
+ provider,
290
+ platformId: senderId
291
+ });
292
+ setCachedResolve(cacheKey, {
293
+ identityId: r.identityId,
294
+ accessAllowed: r.accessAllowed,
295
+ status: r.status
296
+ });
297
+ if (r.identityId == null) {
298
+ log.warn(`Identity not provisioned for ${provider}:${senderId} — blocking inbound message`);
299
+ return {
300
+ block: true,
301
+ blockReason: "Identity: identity not provisioned for this channel"
302
+ };
303
+ }
304
+ if (!r.accessAllowed) return {
305
+ block: true,
306
+ blockReason: "Identity: access denied for this sender"
307
+ };
308
+ log.info(`Identity resolved: ${senderId} → ${r.identityId} (${r.status})`);
309
+ } catch (e) {
310
+ log.error(`Identity resolution failed for ${senderId}: ${e.message}`);
311
+ return {
312
+ block: true,
313
+ blockReason: "Identity: identity service unavailable — access denied (fail-closed)"
314
+ };
315
+ }
316
+ }, { priority: 100 });
317
+ const beforeToolCallStub = (event, ctx) => {
318
+ return Promise.resolve(void 0);
319
+ };
320
+ api.on("before_tool_call", (...args) => beforeToolCallStub(args[0], args[1]), { priority: 100 });
321
+ log.info("Alfe Identity plugin activated");
322
+ }
323
+ };
324
+ //#endregion
325
+ module.exports = plugin;