@ziggs-ai/api-client 0.3.1 → 0.4.0

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 (35) hide show
  1. package/dist/capabilities/artifacts.d.ts +3 -0
  2. package/dist/capabilities/artifacts.js +86 -0
  3. package/dist/capabilities/chat.d.ts +11 -0
  4. package/dist/capabilities/chat.js +38 -0
  5. package/dist/capabilities/connections.d.ts +4 -0
  6. package/dist/capabilities/connections.js +112 -0
  7. package/dist/capabilities/context.d.ts +23 -0
  8. package/dist/capabilities/context.js +220 -0
  9. package/dist/capabilities/discovery.d.ts +4 -0
  10. package/dist/capabilities/discovery.js +77 -0
  11. package/dist/capabilities/grants.d.ts +9 -0
  12. package/dist/capabilities/grants.js +77 -0
  13. package/dist/capabilities/index.d.ts +9 -0
  14. package/dist/capabilities/index.js +9 -0
  15. package/dist/capabilities/links.d.ts +17 -0
  16. package/dist/capabilities/links.js +193 -0
  17. package/dist/capabilities/payments.d.ts +11 -0
  18. package/dist/capabilities/payments.js +404 -0
  19. package/dist/capabilities/types.d.ts +88 -0
  20. package/dist/capabilities/types.js +24 -0
  21. package/dist/http/ConnectionsClient.d.ts +27 -1
  22. package/dist/http/ConnectionsClient.js +29 -0
  23. package/dist/http/GrantsClient.d.ts +16 -0
  24. package/dist/http/GrantsClient.js +3 -0
  25. package/dist/http/OrgsClient.d.ts +36 -0
  26. package/dist/http/OrgsClient.js +61 -0
  27. package/dist/http/PaymentsClient.d.ts +75 -10
  28. package/dist/http/PaymentsClient.js +26 -14
  29. package/dist/http/index.d.ts +5 -5
  30. package/dist/http/index.js +1 -1
  31. package/dist/index.d.ts +1 -0
  32. package/dist/index.js +1 -0
  33. package/package.json +1 -1
  34. package/dist/http/grantRails.d.ts +0 -20
  35. package/dist/http/grantRails.js +0 -50
@@ -0,0 +1,3 @@
1
+ import { type CapabilityDefinition } from './types.js';
2
+ export declare const recordArtifactCapability: CapabilityDefinition;
3
+ export declare const ARTIFACT_CAPABILITIES: CapabilityDefinition[];
@@ -0,0 +1,86 @@
1
+ import { ArtifactsClient } from '../http/ArtifactsClient.js';
2
+ import { fullCreds } from './types.js';
3
+ /**
4
+ * ZIG-560 teaching: name the result slot on the success path so an agent finds
5
+ * the right move unaided — worded in each surface's task grammar (SDK
6
+ * task_update carries the terminal result; MCP has ziggs_set_task_result).
7
+ */
8
+ function reportingHint(env, contentType, taskId) {
9
+ const close = env.surface === 'mcp'
10
+ ? 'ziggs_set_task_result ({ summary, status, links })'
11
+ : 'task_update';
12
+ if (contentType === 'result') {
13
+ return taskId
14
+ ? `Recorded as a task-bound result artifact. Close the task by setting its terminal result with ${close}.`
15
+ : `Recorded as a result artifact, but not bound to a task — pass taskId to bind it, then close the task with ${close}.`;
16
+ }
17
+ return `Reporting finished work? Record it with content_type=result bound to the task (taskId), then close the task with ${close} — chat messages are conversation only.`;
18
+ }
19
+ export const recordArtifactCapability = {
20
+ key: 'record_artifact',
21
+ names: { sdk: 'record_artifact', mcp: 'ziggs_record_artifact' },
22
+ descriptions: {
23
+ sdk: 'Write an artifact to a chat or agreement scope. Set visibility explicitly. For a finished deliverable, set content_type=result and pass taskId to bind it to the task — heavy results belong in artifacts, not chat messages.',
24
+ mcp: 'Write an artifact to a chat or agreement scope. Set visibility explicitly. ' +
25
+ 'For a finished deliverable, set content_type=result and pass taskId to bind it to the task. ' +
26
+ 'Finished work is the task result — set it with ziggs_set_task_result; never report finished work as a chat message (chat is conversation only).',
27
+ },
28
+ annotation: 'write',
29
+ params: {
30
+ text: { type: 'string', required: true, description: 'Artifact body' },
31
+ visibility: {
32
+ type: 'string',
33
+ required: true,
34
+ enum: ['chat', 'agent-private'],
35
+ description: 'chat = visible to scope parties; agent-private = your eyes only',
36
+ },
37
+ chatId: { type: 'string', description: 'Target chat (xor agreementId)' },
38
+ agreementId: { type: 'string', description: 'Target agreement (xor chatId)' },
39
+ taskId: {
40
+ type: 'string',
41
+ description: 'Optional task — creates a TaskArtifactLink alongside the primary scope link',
42
+ },
43
+ content_type: {
44
+ type: 'string',
45
+ description: 'Default text; use result for a finished deliverable',
46
+ },
47
+ idempotencyKey: {
48
+ type: 'string',
49
+ description: 'Optional dedup key: a redelivered record with the same key no-ops and returns the original artifact. Derive it deterministically (e.g. from the source event + step) — not a random value — so a crash-replay reproduces it.',
50
+ },
51
+ },
52
+ needsAgentId: true,
53
+ handler: async (args, env) => {
54
+ const chatId = args['chatId'];
55
+ const agreementId = args['agreementId'];
56
+ if ((chatId && agreementId) || (!chatId && !agreementId)) {
57
+ throw new Error('Pass exactly one of chatId or agreementId');
58
+ }
59
+ const visibility = args['visibility'];
60
+ if (visibility !== 'chat' && visibility !== 'agent-private') {
61
+ throw new Error('visibility must be chat or agent-private');
62
+ }
63
+ const contentType = args['content_type'];
64
+ const taskId = args['taskId'];
65
+ const creds = fullCreds(env);
66
+ const { artifactId } = await new ArtifactsClient(creds.operatorKey, creds.agentId).writeStrict({
67
+ text: args['text'],
68
+ visibility,
69
+ chatId,
70
+ agreementId,
71
+ taskId,
72
+ content_type: contentType,
73
+ idempotencyKey: args['idempotencyKey'],
74
+ });
75
+ return {
76
+ ok: true,
77
+ artifactId,
78
+ visibility,
79
+ chatId,
80
+ agreementId,
81
+ taskId,
82
+ reportingHint: reportingHint(env, contentType, taskId),
83
+ };
84
+ },
85
+ };
86
+ export const ARTIFACT_CAPABILITIES = [recordArtifactCapability];
@@ -0,0 +1,11 @@
1
+ import { type CapabilityDefinition } from './types.js';
2
+ /**
3
+ * ZIG-900 — the decided chat surface for agents: open_conversation only.
4
+ * There is deliberately NO chat-listing tool on the SDK: agents read context
5
+ * only via held grants (ZIG-425) and chat membership auto-mints a chat grant
6
+ * (ZIG-428/426), so "what chats can I see" is already answered by list_grants
7
+ * scopeKind=chat (ZIG-626 rule). MCP keeps its rich session-UX lister
8
+ * (ziggs_list_chats) for humans in Cursor/Claude.
9
+ */
10
+ export declare const openConversationCapability: CapabilityDefinition;
11
+ export declare const CHAT_CAPABILITIES: CapabilityDefinition[];
@@ -0,0 +1,38 @@
1
+ import { openConversation } from '../http/ChatClient.js';
2
+ import { fullCreds } from './types.js';
3
+ /**
4
+ * ZIG-900 — the decided chat surface for agents: open_conversation only.
5
+ * There is deliberately NO chat-listing tool on the SDK: agents read context
6
+ * only via held grants (ZIG-425) and chat membership auto-mints a chat grant
7
+ * (ZIG-428/426), so "what chats can I see" is already answered by list_grants
8
+ * scopeKind=chat (ZIG-626 rule). MCP keeps its rich session-UX lister
9
+ * (ziggs_list_chats) for humans in Cursor/Claude.
10
+ */
11
+ export const openConversationCapability = {
12
+ key: 'open_conversation',
13
+ names: { sdk: 'open_conversation', mcp: 'ziggs_open_conversation' },
14
+ descriptions: {
15
+ sdk: 'Open or reuse a chat with a user or agent participant. To reach an agent in ANOTHER org, establish a link first — request_link (if you have its agent id) or create_link_invite (if you do not), approved/claimed — otherwise this fails with AGENT_NOT_PUBLISHED. To list chats you can already read, use list_grants scopeKind=chat.',
16
+ mcp: 'Open or reuse a chat with a user or agent participant. To reach an agent in ANOTHER org, an unpublished delegate must establish a link first — call ziggs_request_link (if you have its agent id) or ziggs_create_link_invite (if you do not) and have it approved/claimed — otherwise this fails with AGENT_NOT_PUBLISHED.',
17
+ },
18
+ annotation: 'write',
19
+ params: {
20
+ participantId: {
21
+ type: 'string',
22
+ required: true,
23
+ description: 'User or agent id to converse with (from agent search — do not guess ids)',
24
+ },
25
+ },
26
+ needsAgentId: true,
27
+ handler: async (args, env) => {
28
+ if (!args['participantId'])
29
+ throw new Error('participantId is required');
30
+ const { chatId } = await openConversation(args['participantId'], fullCreds(env));
31
+ const lister = env.surface === 'mcp' ? 'ziggs_list_grants' : 'list_grants';
32
+ return {
33
+ chatId,
34
+ note: `Conversation is open (or reused). Your membership auto-mints a chat grant, so the chat also appears in ${lister} scopeKind=chat for context reads.`,
35
+ };
36
+ },
37
+ };
38
+ export const CHAT_CAPABILITIES = [openConversationCapability];
@@ -0,0 +1,4 @@
1
+ import { type CapabilityDefinition } from './types.js';
2
+ export declare const connectionProxyCapability: CapabilityDefinition;
3
+ export declare const requestConnectionCapability: CapabilityDefinition;
4
+ export declare const CONNECTION_CAPABILITIES: CapabilityDefinition[];
@@ -0,0 +1,112 @@
1
+ import { ConnectionsClient } from '../http/ConnectionsClient.js';
2
+ import { rethrowWithContext, } from './types.js';
3
+ function client(env) {
4
+ const { operatorKey, agentId } = env.creds;
5
+ if (!operatorKey)
6
+ throw new Error('operatorKey missing from tool context');
7
+ return new ConnectionsClient(operatorKey, agentId, env.baseUrl);
8
+ }
9
+ export const connectionProxyCapability = {
10
+ key: 'connection_proxy',
11
+ names: { sdk: 'connection_proxy', mcp: 'ziggs_connection_proxy' },
12
+ descriptions: {
13
+ sdk: "Use a stored connection (a third-party credential, e.g. the owner's GitHub/Jira) without ever seeing the credential. Calls the backend connections proxy with a grant the owner issued to this agent: the proxy enforces the grant, decrypts the token server-side, makes the upstream provider call, and returns the result (token-leak guarded on both sides). Provide connectionId, grantId, the provider action (e.g. repo:read), and an optional action-specific payload. Don't know connectionId/grantId yet? Use list_grants (scopeKind=connection) or connection_list_grants first.",
14
+ mcp: "Use a stored connection (a third-party credential, e.g. the owner's GitHub/Jira — NOT an agent-to-agent Link, see ziggs_list_links for that) without ever seeing the credential. " +
15
+ 'Calls the backend connections proxy with a grant the owner issued to this agent: the proxy enforces the grant, decrypts the token server-side, makes the upstream provider call, and returns the result (token-leak guarded on both sides). ' +
16
+ 'Provide connectionId, grantId, the provider action (e.g. repo:read), and an optional action-specific payload. ' +
17
+ "Don't know connectionId/grantId yet? Call ziggs_list_my_connections first.",
18
+ },
19
+ annotation: 'write',
20
+ params: {
21
+ connectionId: { type: 'string', required: true, description: 'Connection to act on' },
22
+ grantId: {
23
+ type: 'string',
24
+ required: true,
25
+ description: 'Grant the owner issued to this agent for the connection',
26
+ },
27
+ action: { type: 'string', required: true, description: 'Provider action, e.g. repo:read' },
28
+ payload: { type: 'object', description: 'Action-specific arguments (provider-defined)' },
29
+ },
30
+ needsAgentId: true,
31
+ handler: async (args, env) => {
32
+ if (!args['connectionId'])
33
+ throw new Error('connectionId is required');
34
+ if (!args['grantId'])
35
+ throw new Error('grantId is required');
36
+ if (!args['action'])
37
+ throw new Error('action is required');
38
+ try {
39
+ const result = await client(env).proxy({
40
+ connectionId: args['connectionId'],
41
+ grantId: args['grantId'],
42
+ action: args['action'],
43
+ payload: args['payload'],
44
+ });
45
+ return { ok: true, action: args['action'], result };
46
+ }
47
+ catch (e) {
48
+ rethrowWithContext(e, 'Connection proxy failed');
49
+ }
50
+ },
51
+ };
52
+ export const requestConnectionCapability = {
53
+ key: 'request_connection',
54
+ names: { sdk: 'request_connection', mcp: 'ziggs_request_connection' },
55
+ descriptions: {
56
+ sdk: 'Ask your principal (the human) to connect a remote MCP server and grant you the listed tools. Opens a connection-consent agreement as an approvable card in the chat you pass — the human approves it there like any other agreement. On approval the server is connected (browser OAuth if needed) and you are granted the tools; use them via connection_proxy.',
57
+ mcp: 'Ask your principal (the human) to connect a remote MCP server and grant you the listed tools. ' +
58
+ 'Opens a connection-consent agreement as an approvable card in the chat you pass — the human approves it there like any other agreement (there is no MCP tool to approve it, so tell them to approve it in the chat). ' +
59
+ 'On approval the server is connected (browser OAuth if needed) and you are granted the tools; the result shows up in ziggs_list_my_connections for use with ziggs_connection_proxy.',
60
+ },
61
+ annotation: 'write',
62
+ params: {
63
+ chatId: {
64
+ type: 'string',
65
+ required: true,
66
+ description: 'The chat you are working in — the consent card is opened there',
67
+ },
68
+ serverUrl: { type: 'string', required: true, description: 'Remote MCP server URL (https)' },
69
+ tools: {
70
+ type: 'array',
71
+ items: { type: 'string' },
72
+ required: true,
73
+ description: "Tool names you want — become the grant's allowed_actions caveats",
74
+ },
75
+ reason: { type: 'string', description: 'Plain-language reason shown to the human deciding' },
76
+ },
77
+ needsAgentId: true,
78
+ handler: async (args, env) => {
79
+ if (!args['chatId'])
80
+ throw new Error('chatId is required');
81
+ if (!args['serverUrl'])
82
+ throw new Error('serverUrl is required');
83
+ const tools = args['tools'];
84
+ if (!Array.isArray(tools) || tools.length === 0) {
85
+ throw new Error('tools must be a non-empty array of tool names');
86
+ }
87
+ try {
88
+ const result = await client(env).requestMcpConnection({
89
+ chatId: args['chatId'],
90
+ serverUrl: args['serverUrl'],
91
+ tools: tools,
92
+ reason: args['reason'],
93
+ });
94
+ return {
95
+ ok: true,
96
+ ...result,
97
+ note: env.surface === 'mcp'
98
+ ? 'A connection-consent card is now in the chat awaiting your principal. Tell the human now (pull-only MCP has no push) — they approve it right in the chat. ' +
99
+ 'Once approved, the connection + grant appear in ziggs_list_my_connections for ziggs_connection_proxy.'
100
+ : 'A connection-consent card is now in the chat awaiting your principal — they approve it right there (ZIG-798 flow). ' +
101
+ 'Once approved, the connection + grant appear in list_grants (scopeKind=connection) / connection_list_grants for connection_proxy.',
102
+ };
103
+ }
104
+ catch (e) {
105
+ rethrowWithContext(e, 'Connection request failed');
106
+ }
107
+ },
108
+ };
109
+ export const CONNECTION_CAPABILITIES = [
110
+ connectionProxyCapability,
111
+ requestConnectionCapability,
112
+ ];
@@ -0,0 +1,23 @@
1
+ import { type GrantView } from '../http/grants.js';
2
+ import { type CapabilityDefinition, type CapabilityEnv } from './types.js';
3
+ /**
4
+ * Human/LLM-readable bounds for a context grant. ZIG-646 folded a context
5
+ * grant's temporal mode + read watermark into the canonical `caveats` array,
6
+ * so pull them back out here to keep the `bounds` summary stable.
7
+ */
8
+ export declare function contextBounds(grant: GrantView): Record<string, unknown>;
9
+ /**
10
+ * ZIG-941 #6 — org-scoped grants may name the org instead of pasting its
11
+ * opaque org_... id: exact id or case-insensitive name against the operator's
12
+ * memberships. Ambiguous names throw with the candidate list rather than
13
+ * guessing; a name that matched nothing throws with a pointer to the org
14
+ * lister. An org_... id that is not a membership passes through unchanged —
15
+ * you may hold a grant on an org you do not belong to, so the server stays
16
+ * the authority on the id.
17
+ */
18
+ export declare function resolveOrgScopeId(env: CapabilityEnv, scopeId: string): Promise<string>;
19
+ export declare const contextReadCapability: CapabilityDefinition;
20
+ export declare const contextExpandReachCapability: CapabilityDefinition;
21
+ export declare const contextDiscoverGrantableCapability: CapabilityDefinition;
22
+ export declare const contextDelegateCapability: CapabilityDefinition;
23
+ export declare const CONTEXT_CAPABILITIES: CapabilityDefinition[];
@@ -0,0 +1,220 @@
1
+ import { ContextReadClient } from '../http/ContextReadClient.js';
2
+ import { ContextGrantsClient, } from '../http/ContextGrantsClient.js';
3
+ import { ContextDiscoveryClient } from '../http/ContextDiscoveryClient.js';
4
+ import { grantCaveat } from '../http/grants.js';
5
+ import { fetchMyOrgs, resolveOrgSelector } from '../http/OrgsClient.js';
6
+ import { fullCreds } from './types.js';
7
+ const CONTEXT_READ_TYPES = [
8
+ 'messages',
9
+ 'artifacts',
10
+ 'agreements',
11
+ 'tasks',
12
+ ];
13
+ const GRANT_SCOPE_KINDS = ['chat', 'agreement', 'org'];
14
+ const CONTEXT_TEMPORALS = ['from-now', 'from-start'];
15
+ /**
16
+ * Human/LLM-readable bounds for a context grant. ZIG-646 folded a context
17
+ * grant's temporal mode + read watermark into the canonical `caveats` array,
18
+ * so pull them back out here to keep the `bounds` summary stable.
19
+ */
20
+ export function contextBounds(grant) {
21
+ return {
22
+ temporal: grantCaveat(grant, 'temporal'),
23
+ watermarkAt: grantCaveat(grant, 'watermark_at'),
24
+ expiresAt: grant.expiresAt,
25
+ };
26
+ }
27
+ /**
28
+ * ZIG-941 #6 — org-scoped grants may name the org instead of pasting its
29
+ * opaque org_... id: exact id or case-insensitive name against the operator's
30
+ * memberships. Ambiguous names throw with the candidate list rather than
31
+ * guessing; a name that matched nothing throws with a pointer to the org
32
+ * lister. An org_... id that is not a membership passes through unchanged —
33
+ * you may hold a grant on an org you do not belong to, so the server stays
34
+ * the authority on the id.
35
+ */
36
+ export async function resolveOrgScopeId(env, scopeId) {
37
+ const resolution = resolveOrgSelector(await fetchMyOrgs(fullCreds(env), env.baseUrl), scopeId);
38
+ if (resolution.status === 'ok')
39
+ return resolution.orgId;
40
+ if (resolution.status === 'ambiguous') {
41
+ throw new Error(`Org name "${scopeId}" matches ${resolution.matches.length} of your orgs — pass the org id: ` +
42
+ resolution.matches.map((m) => `${m.name} (${m.orgId})`).join(', '));
43
+ }
44
+ if (scopeId.startsWith('org_'))
45
+ return scopeId;
46
+ const lister = env.surface === 'mcp' ? 'ziggs_list_my_orgs' : 'your org list';
47
+ throw new Error(`No org named "${scopeId}" in your memberships — use ${lister} to see them, or pass the org id.`);
48
+ }
49
+ export const contextReadCapability = {
50
+ key: 'context_read',
51
+ names: { sdk: 'context_read', mcp: 'ziggs_read_context' },
52
+ descriptions: {
53
+ sdk: 'Read the contents of a scope you already hold a grant for: messages | artifacts | agreements | tasks. Use list_grants first to see which scopes your grants cover, then read through any of them. Cursored; all access is grant-fenced server-side.',
54
+ mcp: 'Read the contents of a scope you already hold: messages | artifacts | agreements | tasks (the type param), under via=chat:<id>, agreement:<id>, or task:<id>. Forward-delta with after+direction=forward; cursor pagination; contextGrantId pins a grant. The response carries a `readPlan` with the next page and/or forward-delta call pre-filled (after=this page\'s latestSequence), so you can keep reading without rebuilding args. This is the single read path for all four types — to discover which scopes exist (your chats / tasks / agreements / grants / links), use the ziggs_list_* tools.',
55
+ },
56
+ annotation: 'read-only',
57
+ params: {
58
+ type: {
59
+ type: 'string',
60
+ required: true,
61
+ enum: CONTEXT_READ_TYPES,
62
+ description: 'Resource type to read from the scope',
63
+ },
64
+ via: {
65
+ type: 'string',
66
+ required: true,
67
+ description: 'Scope entry you hold, e.g. chat:<id>, agreement:<id>, task:<id>',
68
+ },
69
+ cursor: { type: 'string', description: 'Opaque cursor from a prior nextCursor to page' },
70
+ after: { type: 'string', description: 'ISO timestamp for forward-delta (messages/artifacts)' },
71
+ direction: {
72
+ type: 'string',
73
+ enum: ['forward'],
74
+ description: 'Use "forward" with after for a message forward-delta',
75
+ },
76
+ limit: { type: 'number', description: 'Page size (server default when omitted)' },
77
+ state: { type: 'string', description: 'Task state filter (tasks only)' },
78
+ contextGrantId: {
79
+ type: 'string',
80
+ description: 'Pin a specific grant when you hold several over the same scope',
81
+ },
82
+ },
83
+ needsAgentId: true,
84
+ handler: async (args, env) => {
85
+ const creds = fullCreds(env);
86
+ const type = args['type'];
87
+ if (!CONTEXT_READ_TYPES.includes(type)) {
88
+ throw new Error(`type must be one of ${CONTEXT_READ_TYPES.join(', ')}`);
89
+ }
90
+ const via = args['via'];
91
+ if (!via)
92
+ throw new Error('via is required');
93
+ const direction = args['direction'];
94
+ if (direction !== undefined && direction !== 'forward') {
95
+ throw new Error('direction must be "forward"');
96
+ }
97
+ return new ContextReadClient(creds.operatorKey, creds.agentId).read(type, {
98
+ via,
99
+ cursor: args['cursor'],
100
+ after: args['after'],
101
+ direction: direction,
102
+ limit: typeof args['limit'] === 'number' ? args['limit'] : undefined,
103
+ state: args['state'],
104
+ contextGrantId: args['contextGrantId'],
105
+ });
106
+ },
107
+ };
108
+ export const contextExpandReachCapability = {
109
+ key: 'context_expand_reach',
110
+ names: { sdk: 'context_expand_reach', mcp: 'ziggs_expand_context' },
111
+ descriptions: {
112
+ sdk: 'Expand a grant you hold into the chat/agreement ids inside its scope, so you can read through it. list_grants tells you that you hold e.g. org:acme or agreement:x; this returns the actual { chats, agreements } (ids + labels only, no content) that scope covers — feed an id to context_read (via=chat:<id> / agreement:<id>). Org scope is capped: truncatedChats/truncatedAgreements say how many were left off. Holder-only, grant-fenced.',
113
+ mcp: 'Expand a grant you hold into the chat/agreement ids inside its scope, so you can actually read through it. ziggs_list_grants tells you that you hold e.g. org:acme or agreement:x; this returns the { chats, agreements } (ids + labels only, never content) that scope covers — feed an id to ziggs_read_context (via=chat:<id> / agreement:<id>). Org scope is capped: truncatedChats/truncatedAgreements say how many were left off. Holder-only, grant-fenced.',
114
+ },
115
+ annotation: 'read-only',
116
+ params: {
117
+ grantId: {
118
+ type: 'string',
119
+ required: true,
120
+ description: 'A grant you hold (grantId from the grant lister) to expand',
121
+ },
122
+ },
123
+ needsAgentId: true,
124
+ handler: async (args, env) => {
125
+ const creds = fullCreds(env);
126
+ const grantId = args['grantId'];
127
+ if (!grantId)
128
+ throw new Error('grantId is required');
129
+ return new ContextGrantsClient(creds.operatorKey, creds.agentId).getReach(grantId);
130
+ },
131
+ };
132
+ export const contextDiscoverGrantableCapability = {
133
+ key: 'context_discover_grantable',
134
+ names: { sdk: 'context_discover_grantable', mcp: 'ziggs_discover_grantable' },
135
+ descriptions: {
136
+ sdk: 'See what context EXISTS in your orgs that you CANNOT read yet — the inverse of list_grants. Covers chats, agreements, and connections (type is one of "chat" | "agreement" | "connection"; connection labels are the provider name only). Returns labels only ({ type, label, scopeRef, orgId } per item), never content, member names, tokens, or money. Bounded to orgs you have an active agreement in, and excludes anything you already hold a grant for. Use it to notice you may be missing context, then either ask your human to grant a scopeRef, or (if you hold a broader grant) context_delegate using that scopeRef. Pair with list_grants (what you hold) and context_expand_reach (what a held grant covers).',
137
+ mcp: 'See what context EXISTS in your orgs that you CANNOT read yet — so you can ask for it instead of failing blind. Covers chats, agreements, and connections (type is "chat" | "agreement" | "connection"; connection labels are the provider name only). Returns labels only: { type, label, scopeRef, orgId } per item, never content, member names, tokens, or money. Bounded to orgs you have an active agreement in. To act on one, ask your human to grant it, or (if you hold a broader grant of your own) delegate via ziggs_delegate_grant using the scopeRef. Use ziggs_list_grants for what you already hold; this is what you lack.',
138
+ },
139
+ annotation: 'read-only',
140
+ params: {},
141
+ needsAgentId: true,
142
+ handler: async (_args, env) => {
143
+ const creds = fullCreds(env);
144
+ const items = await new ContextDiscoveryClient(creds.operatorKey, creds.agentId).discoverGrantable();
145
+ return { count: items.length, items };
146
+ },
147
+ };
148
+ export const contextDelegateCapability = {
149
+ key: 'context_delegate',
150
+ names: { sdk: 'context_delegate', mcp: 'ziggs_delegate_grant' },
151
+ descriptions: {
152
+ sdk: 'Delegate a narrower child context grant (tighter scope, shorter expiry, or from-now). Holder-only. Delegating a grant whose original owner is another party opens an approval request rather than minting immediately (status: pending_approval).',
153
+ mcp: 'Delegate a narrower child grant from one you hold (POST /context/grants/:id/delegate). Delegation only narrows scope/expiry/temporal — never broadens. If the grant\'s original owner is a different party, this does NOT grant — it opens a request that owner must approve, and returns { status: "pending_approval", agreementId }; surface that to the human and do not treat it as done.',
154
+ },
155
+ annotation: 'write',
156
+ params: {
157
+ parentGrantId: { type: 'string', required: true },
158
+ holderId: { type: 'string', required: true, description: 'Agent receiving the delegated grant' },
159
+ scopeKind: { type: 'string', required: true, enum: GRANT_SCOPE_KINDS },
160
+ scopeId: { type: 'string', required: true },
161
+ temporal: {
162
+ type: 'string',
163
+ required: true,
164
+ enum: CONTEXT_TEMPORALS,
165
+ description: 'from-now or from-start (must be same-or-narrower)',
166
+ },
167
+ expiresAt: { type: 'string' },
168
+ watermarkAt: {
169
+ type: 'string',
170
+ description: 'from-now watermark ISO-8601 (optional; server may default)',
171
+ },
172
+ },
173
+ needsAgentId: true,
174
+ handler: async (args, env) => {
175
+ const creds = fullCreds(env);
176
+ const temporal = args['temporal'];
177
+ if (!CONTEXT_TEMPORALS.includes(temporal)) {
178
+ throw new Error('temporal must be from-now or from-start');
179
+ }
180
+ const scopeKind = args['scopeKind'];
181
+ if (!GRANT_SCOPE_KINDS.includes(scopeKind)) {
182
+ throw new Error('scopeKind must be chat, agreement, or org');
183
+ }
184
+ // ZIG-941 #6 — an org scope may be named rather than pasted as org_… id.
185
+ let scopeId = args['scopeId'];
186
+ if (scopeKind === 'org') {
187
+ scopeId = await resolveOrgScopeId(env, scopeId);
188
+ }
189
+ const client = new ContextGrantsClient(creds.operatorKey, creds.agentId);
190
+ const result = await client.delegateGrant(args['parentGrantId'], {
191
+ holderId: args['holderId'],
192
+ scope: { kind: scopeKind, id: scopeId },
193
+ temporal: temporal,
194
+ expiresAt: args['expiresAt'] ?? undefined,
195
+ watermarkAt: args['watermarkAt'],
196
+ });
197
+ if (result.status === 'pending_approval') {
198
+ return {
199
+ status: 'pending_approval',
200
+ message: "This grant's original owner must approve sharing it. A request was opened for them — surface it to the human; nothing is granted yet.",
201
+ parentGrantId: args['parentGrantId'],
202
+ agreementId: result.agreementId,
203
+ ownerId: result.ownerId,
204
+ };
205
+ }
206
+ const grant = result.grant;
207
+ return {
208
+ status: 'delegated',
209
+ parentGrantId: args['parentGrantId'],
210
+ grant,
211
+ bounds: contextBounds(grant),
212
+ };
213
+ },
214
+ };
215
+ export const CONTEXT_CAPABILITIES = [
216
+ contextReadCapability,
217
+ contextDelegateCapability,
218
+ contextExpandReachCapability,
219
+ contextDiscoverGrantableCapability,
220
+ ];
@@ -0,0 +1,4 @@
1
+ import { type CapabilityDefinition } from './types.js';
2
+ export declare const agentSearchCapability: CapabilityDefinition;
3
+ export declare const agentGetCapability: CapabilityDefinition;
4
+ export declare const DISCOVERY_CAPABILITIES: CapabilityDefinition[];
@@ -0,0 +1,77 @@
1
+ import { AgentSearchClient } from '../http/AgentSearchClient.js';
2
+ import { fullCreds } from './types.js';
3
+ export const agentSearchCapability = {
4
+ key: 'agent_search',
5
+ names: { sdk: 'agent_search', mcp: 'ziggs_search_agents' },
6
+ descriptions: {
7
+ sdk: 'Search for agents by capability, name, or description. Returns ranked results with relevance scores. A keyword/natural-language query searches the published store AND, scoped to your authority, your own org-mates and any delegate you have an active link with. Passing an EXACT agent id resolves that one agent even if unpublished/private. Use before agreement_propose or agreement_subcontract to discover the right agent for a job; use returned agentId in grant/issue tools — do not guess ids.',
8
+ mcp: 'Find agents (AgentSearchClient). A keyword/natural-language query searches the published store AND, scoped to your authority, your own org-mates and any delegate you have an active link with — so you can find a teammate or another user\'s delegate by name and ziggs_open_conversation with it directly, even if it is unpublished/offline and has never been in a chat with you. Passing an EXACT agent id resolves that one agent even if unpublished/private — use this for a delegate someone shared an id for, then ziggs_request_link if not yet linked. Each result carries a per-row `reachability` field derived from HOW you can reach it — `published` (store directory), `same-org`, `linked`, or `managed`; it is not a blanket "published" label. If an exact-id lookup matches an unpublished agent you cannot reach, the row is `reachability: "restricted"` and returns the id only with no name/profile. Use returned agentId in grant/issue tools — do not guess ids.',
9
+ },
10
+ annotation: 'read-only',
11
+ params: {
12
+ query: {
13
+ type: 'string',
14
+ required: true,
15
+ description: 'Keyword/natural-language search (published store + your org-mates + your linked delegates) OR an exact agent id (resolves that agent even if unpublished, when you can reach it)',
16
+ },
17
+ limit: { type: 'number', description: 'Max results (default server-side)' },
18
+ minScore: { type: 'number', description: 'Minimum match score filter' },
19
+ },
20
+ needsAgentId: true,
21
+ handler: async (args, env) => {
22
+ if (!args['query'])
23
+ throw new Error('query is required');
24
+ const creds = fullCreds(env);
25
+ const client = new AgentSearchClient(creds.operatorKey, creds.agentId);
26
+ const result = await client.searchAgents(args['query'], {
27
+ limit: typeof args['limit'] === 'number' ? args['limit'] : undefined,
28
+ minScore: typeof args['minScore'] === 'number' ? args['minScore'] : undefined,
29
+ });
30
+ if (!result.success) {
31
+ throw new Error(result.error ?? result.message ?? 'search failed');
32
+ }
33
+ if (!result.agents?.length) {
34
+ // ZIG-664: a bare {count: 0} reads as "discovery is down" to LLM
35
+ // callers — say what was searched and how to recover instead.
36
+ return {
37
+ count: 0,
38
+ agents: [],
39
+ searched: ['published store', 'your org-mates', 'your linked delegates'],
40
+ hint: 'Zero hits means no agent profile matched these terms — discovery itself is up. ' +
41
+ 'Matching is lexical against agent name/description/tags, so try shorter or different keywords. ' +
42
+ 'If you already know the agent, pass its exact agent id as the query to resolve it directly.',
43
+ };
44
+ }
45
+ return { count: result.agents.length, agents: result.agents };
46
+ },
47
+ sdkOptions: { isGenericFallback: true },
48
+ };
49
+ export const agentGetCapability = {
50
+ key: 'agent_get',
51
+ names: { sdk: 'agent_get', mcp: 'ziggs_get_agent' },
52
+ descriptions: {
53
+ sdk: 'Fetch the full profile of a specific agent by ID — name, description, tags, capabilities, reachability, and reliability. Use to confirm capabilities and terms before proposing an agreement, when you already hold the agent id. An id you cannot reach returns reachability "restricted" (id only, no profile). To find an agent by keyword instead, use agent_search.',
54
+ mcp: 'Fetch the full profile of ONE agent by its exact id (GET /agents/:id) — name, description, tags, capabilities, reachability, and reliability. Use to confirm a candidate before ziggs_propose_agreement / ziggs_request_link, when you already hold the agent id (from ziggs_search_agents, a grant, or an agreement party). Grant-scoped: an id you cannot reach returns reachability "restricted" (id only, no profile). To find an agent by keyword instead, use ziggs_search_agents.',
55
+ },
56
+ annotation: 'read-only',
57
+ params: {
58
+ agentId: { type: 'string', required: true, description: 'Exact agent id to fetch — do not guess' },
59
+ },
60
+ needsAgentId: true,
61
+ handler: async (args, env) => {
62
+ if (!args['agentId'])
63
+ throw new Error('agentId is required');
64
+ const creds = fullCreds(env);
65
+ const client = new AgentSearchClient(creds.operatorKey, creds.agentId);
66
+ const result = await client.getAgentById(args['agentId']);
67
+ if (!result.success) {
68
+ throw new Error(result.error ?? 'agent not found');
69
+ }
70
+ const { success: _success, ...agent } = result;
71
+ return { agent };
72
+ },
73
+ };
74
+ export const DISCOVERY_CAPABILITIES = [
75
+ agentSearchCapability,
76
+ agentGetCapability,
77
+ ];
@@ -0,0 +1,9 @@
1
+ import { type CapabilityDefinition } from './types.js';
2
+ /**
3
+ * ZIG-893 — the single "what authority do I hold?" tool. One name, every rail
4
+ * (context chat/agreement/org, connection, wallet), holder-scoped,
5
+ * cross-session. `unreadableRails` comes from the backend (ZIG-956) so a short
6
+ * list is never presented as complete when the key can't read a rail.
7
+ */
8
+ export declare const listGrantsCapability: CapabilityDefinition;
9
+ export declare const GRANTS_CAPABILITIES: CapabilityDefinition[];