@ton-agent-kit/plugin-identity 1.0.0 → 1.1.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.
@@ -0,0 +1,114 @@
1
+ import { z } from "zod";
2
+ import { defineAction } from "@ton-agent-kit/core";
3
+
4
+ export const processPendingRatingsAction = defineAction({
5
+ name: "process_pending_ratings",
6
+ description:
7
+ "Process pending reputation ratings left by completed escrow deals. Each escrow completion (release, auto-release, refund) creates pending ratings for both buyer and seller. Call this to review or auto-submit them.",
8
+ schema: z.object({
9
+ autoSubmit: z
10
+ .boolean()
11
+ .optional()
12
+ .describe("Automatically submit all pending ratings with suggested success values. Defaults to false (returns pending list for review)."),
13
+ }),
14
+ handler: async (agent, params) => {
15
+ // Load pending ratings from memory
16
+ let entries: any[] = [];
17
+ try {
18
+ const r = await (agent as any).runAction("list_context", {
19
+ namespace: "pending_ratings",
20
+ });
21
+ entries = r.entries || [];
22
+ } catch {
23
+ return {
24
+ processed: 0,
25
+ pending: 0,
26
+ ratings: [],
27
+ message: "Memory plugin not available. Cannot process pending ratings.",
28
+ };
29
+ }
30
+
31
+ if (entries.length === 0) {
32
+ return {
33
+ processed: 0,
34
+ pending: 0,
35
+ ratings: [],
36
+ message: "No pending ratings to process.",
37
+ };
38
+ }
39
+
40
+ // Parse entries
41
+ const pending: any[] = [];
42
+ for (const entry of entries) {
43
+ try {
44
+ const data = JSON.parse(entry.value);
45
+ pending.push({ ...data, memoryKey: entry.key });
46
+ } catch {
47
+ continue;
48
+ }
49
+ }
50
+
51
+ if (!params.autoSubmit) {
52
+ return {
53
+ processed: 0,
54
+ pending: pending.length,
55
+ ratings: pending.map((p) => ({
56
+ escrowId: p.escrowId,
57
+ raterRole: p.raterRole,
58
+ targetAddress: p.targetAddress,
59
+ suggestedSuccess: p.suggestedSuccess,
60
+ escrowOutcome: p.escrowOutcome,
61
+ })),
62
+ message: `${pending.length} pending rating(s) found. Set autoSubmit=true to submit them.`,
63
+ };
64
+ }
65
+
66
+ // Auto-submit ratings
67
+ let processed = 0;
68
+ const results: any[] = [];
69
+
70
+ for (const rating of pending) {
71
+ try {
72
+ // Find the target agent ID by address match in the registry
73
+ // Use a simple name-based lookup: the target address is stored in the rating
74
+ await (agent as any).runAction("get_agent_reputation", {
75
+ agentId: rating.targetAddress,
76
+ addTask: true,
77
+ success: rating.suggestedSuccess,
78
+ });
79
+
80
+ // Delete the processed rating from memory
81
+ try {
82
+ await (agent as any).runAction("delete_context", {
83
+ key: rating.memoryKey,
84
+ namespace: "pending_ratings",
85
+ });
86
+ } catch {}
87
+
88
+ processed++;
89
+ results.push({
90
+ escrowId: rating.escrowId,
91
+ raterRole: rating.raterRole,
92
+ targetAddress: rating.targetAddress,
93
+ success: rating.suggestedSuccess,
94
+ submitted: true,
95
+ });
96
+ } catch (err: any) {
97
+ results.push({
98
+ escrowId: rating.escrowId,
99
+ raterRole: rating.raterRole,
100
+ targetAddress: rating.targetAddress,
101
+ submitted: false,
102
+ error: err.message,
103
+ });
104
+ }
105
+ }
106
+
107
+ return {
108
+ processed,
109
+ pending: pending.length - processed,
110
+ ratings: results,
111
+ message: `Processed ${processed}/${pending.length} ratings.`,
112
+ };
113
+ },
114
+ });
@@ -1,69 +1,125 @@
1
1
  import { z } from "zod";
2
- import { defineAction, toFriendlyAddress } from "@ton-agent-kit/core";
2
+ import { Address, internal, toNano } from "@ton/core";
3
+ import { defineAction, toFriendlyAddress, sendTransaction } from "@ton-agent-kit/core";
3
4
  import { loadAgentRegistry, saveAgentRegistry } from "../utils";
5
+ import { resolveContractAddress } from "../reputation-config";
6
+ import { buildRegisterBody } from "../reputation-helpers";
4
7
 
5
- export const registerAgentAction = defineAction({
6
- name: "register_agent",
7
- description:
8
- "Register an AI agent in the local agent registry with its capabilities, name, and description. Other agents can discover it via discover_agent.",
9
- schema: z.object({
10
- name: z
11
- .string()
12
- .describe("Agent name (e.g., 'market-data', 'trading-bot')"),
13
- capabilities: z
14
- .union([z.array(z.string()), z.string()])
15
- .describe(
16
- "List of capabilities (e.g., ['price_feed', 'analytics', 'trading'])",
17
- ),
18
- description: z
19
- .string()
20
- .optional()
21
- .describe("Human-readable description of the agent"),
22
- endpoint: z
23
- .string()
24
- .optional()
25
- .describe("API endpoint where the agent can be reached"),
26
- }),
27
- handler: async (agent, params) => {
28
- const agentId = `agent_${params.name.toLowerCase().replace(/[^a-z0-9]/g, "-")}`;
8
+ export function createRegisterAgentAction(contractAddress?: string) {
9
+ return defineAction({
10
+ name: "register_agent",
11
+ description:
12
+ "Register an AI agent with its capabilities, name, and description. Other agents can discover it via discover_agent. Supports both on-chain (Tact contract) and local JSON modes.",
13
+ schema: z.object({
14
+ name: z
15
+ .string()
16
+ .describe("Agent name (e.g., 'market-data', 'trading-bot')"),
17
+ capabilities: z
18
+ .union([z.array(z.string()), z.string()])
19
+ .describe("List of capabilities (e.g., ['price_feed', 'analytics', 'trading'])"),
20
+ description: z.string().optional().describe("Human-readable description of the agent"),
21
+ endpoint: z.string().optional().describe("API endpoint where the agent can be reached"),
22
+ available: z
23
+ .boolean()
24
+ .optional()
25
+ .describe("Whether the agent is currently available. Defaults to true."),
26
+ }),
27
+ handler: async (agent, params) => {
28
+ const agentId = `agent_${params.name.toLowerCase().replace(/[^a-z0-9]/g, "-")}`;
29
29
 
30
- // Coerce string capabilities to array
31
- let capabilities: string[];
32
- if (typeof params.capabilities === "string") {
33
- try {
34
- capabilities = JSON.parse(params.capabilities);
35
- } catch {
36
- capabilities = params.capabilities.split(",").map((c: string) => c.trim());
30
+ // Coerce capabilities
31
+ let capabilities: string[];
32
+ if (typeof params.capabilities === "string") {
33
+ try {
34
+ capabilities = JSON.parse(params.capabilities);
35
+ } catch {
36
+ capabilities = params.capabilities.split(",").map((c: string) => c.trim());
37
+ }
38
+ } else {
39
+ capabilities = params.capabilities;
37
40
  }
38
- } else {
39
- capabilities = params.capabilities;
40
- }
41
41
 
42
- const agentRecord = {
43
- id: agentId,
44
- name: params.name,
45
- address: agent.wallet.address.toRawString(),
46
- capabilities,
47
- description: params.description || "",
48
- endpoint: params.endpoint || null,
49
- network: agent.network,
50
- registeredAt: new Date().toISOString(),
51
- reputation: { score: 0, totalTasks: 0, successfulTasks: 0 },
52
- };
42
+ const available = params.available !== false;
53
43
 
54
- const registry = loadAgentRegistry();
55
- registry[agentId] = agentRecord;
56
- saveAgentRegistry(registry);
44
+ // Resolve contract address (factory → config → default → null)
45
+ const addr = resolveContractAddress(contractAddress, agent.network);
57
46
 
58
- return {
59
- agentId,
60
- name: params.name,
61
- address: agent.wallet.address.toRawString(),
62
- friendlyAddress: toFriendlyAddress(agent.wallet.address, agent.network),
63
- capabilities,
64
- description: params.description || "",
65
- status: "registered",
66
- dnsHint: `${params.name}.agents.ton (requires TON DNS domain)`,
67
- };
68
- },
69
- });
47
+ // Always save to JSON registry (needed for discovery — contract doesn't store names/capabilities)
48
+ const agentRecord = {
49
+ id: agentId,
50
+ name: params.name,
51
+ address: agent.wallet.address.toRawString(),
52
+ capabilities,
53
+ description: params.description || "",
54
+ endpoint: params.endpoint || null,
55
+ available,
56
+ network: agent.network,
57
+ registeredAt: new Date().toISOString(),
58
+ reputation: { score: 0, totalTasks: 0, successfulTasks: 0 },
59
+ };
60
+
61
+ const registry = loadAgentRegistry();
62
+ registry[agentId] = agentRecord;
63
+ saveAgentRegistry(registry);
64
+
65
+ // ── On-chain mode ──
66
+ if (addr) {
67
+ try {
68
+ const capStr = capabilities.join(",");
69
+ const body = buildRegisterBody(params.name, capStr, available);
70
+
71
+ await sendTransaction(agent, [
72
+ internal({
73
+ to: Address.parse(addr),
74
+ value: toNano("0.03"),
75
+ bounce: true,
76
+ body,
77
+ }),
78
+ ]);
79
+
80
+ return {
81
+ agentId,
82
+ name: params.name,
83
+ address: agent.wallet.address.toRawString(),
84
+ friendlyAddress: toFriendlyAddress(agent.wallet.address, agent.network),
85
+ capabilities,
86
+ available,
87
+ onChain: true,
88
+ contractAddress: addr,
89
+ status: "registered (on-chain + local)",
90
+ message: `Agent "${params.name}" registered on-chain at ${addr.slice(0, 16)}... and locally`,
91
+ };
92
+ } catch (err: any) {
93
+ // On-chain failed but JSON saved — return partial success
94
+ return {
95
+ agentId,
96
+ name: params.name,
97
+ address: agent.wallet.address.toRawString(),
98
+ friendlyAddress: toFriendlyAddress(agent.wallet.address, agent.network),
99
+ capabilities,
100
+ available,
101
+ onChain: false,
102
+ status: "registered (local only — on-chain failed)",
103
+ message: `Agent "${params.name}" saved locally. On-chain registration failed: ${err.message?.slice(0, 80)}`,
104
+ };
105
+ }
106
+ }
107
+
108
+ // ── JSON-only mode ──
109
+ return {
110
+ agentId,
111
+ name: params.name,
112
+ address: agent.wallet.address.toRawString(),
113
+ friendlyAddress: toFriendlyAddress(agent.wallet.address, agent.network),
114
+ capabilities,
115
+ available,
116
+ onChain: false,
117
+ description: params.description || "",
118
+ status: "registered",
119
+ dnsHint: `${params.name}.agents.ton (requires TON DNS domain)`,
120
+ };
121
+ },
122
+ });
123
+ }
124
+
125
+ export const registerAgentAction = createRegisterAgentAction();
@@ -0,0 +1,43 @@
1
+ import { z } from "zod";
2
+ import { Address, internal, toNano, beginCell } from "@ton/core";
3
+ import { defineAction, sendTransaction } from "@ton-agent-kit/core";
4
+ import { resolveContractAddress } from "../reputation-config";
5
+ import { storeTriggerCleanup } from "../contracts/Reputation_Reputation";
6
+
7
+ export const triggerCleanupAction = defineAction({
8
+ name: "trigger_cleanup",
9
+ description:
10
+ "Manually trigger cleanup of inactive, ghost, or low-score agents from the reputation contract. " +
11
+ "Cleanup also runs automatically on every registration and rating. " +
12
+ "Conditions: score<20 with 100+ ratings, inactive 30+ days, ghost (0 ratings after 7 days).",
13
+ schema: z.object({
14
+ maxClean: z.coerce.number().optional().describe("Max agents to clean. Default 10, max 50."),
15
+ }),
16
+ handler: async (agent, params) => {
17
+ const addr = resolveContractAddress(undefined, agent.network);
18
+ if (!addr) {
19
+ return { triggered: false, message: "No reputation contract configured" };
20
+ }
21
+
22
+ const maxClean = Math.min(params.maxClean || 10, 50);
23
+ const body = beginCell()
24
+ .store(storeTriggerCleanup({ $$type: "TriggerCleanup", maxClean: BigInt(maxClean) }))
25
+ .endCell();
26
+
27
+ await sendTransaction(agent, [
28
+ internal({
29
+ to: Address.parse(addr),
30
+ value: toNano("0.03"),
31
+ bounce: true,
32
+ body,
33
+ }),
34
+ ]);
35
+
36
+ return {
37
+ triggered: true,
38
+ maxClean,
39
+ contractAddress: addr,
40
+ message: `Cleanup triggered for up to ${maxClean} agents.`,
41
+ };
42
+ },
43
+ });
@@ -0,0 +1,52 @@
1
+ import { z } from "zod";
2
+ import { Address, internal, toNano } from "@ton/core";
3
+ import { defineAction, sendTransaction } from "@ton-agent-kit/core";
4
+ import { loadReputationConfig } from "../reputation-config";
5
+ import { buildWithdrawBody } from "../reputation-helpers";
6
+
7
+ export function createWithdrawReputationFeesAction(contractAddress?: string) {
8
+ return defineAction({
9
+ name: "withdraw_reputation_fees",
10
+ description:
11
+ "Withdraw accumulated fees from the on-chain Reputation contract. Only the contract owner (deployer) can call this.",
12
+ schema: z.object({
13
+ confirm: z.boolean().optional().describe("Set to true to confirm the withdrawal. Defaults to true."),
14
+ }),
15
+ handler: async (agent, _params) => {
16
+ const addr = contractAddress || loadReputationConfig()?.contractAddress;
17
+ if (!addr) {
18
+ return {
19
+ withdrawn: false,
20
+ message: "No reputation contract deployed. Run deploy_reputation_contract first.",
21
+ };
22
+ }
23
+
24
+ try {
25
+ const body = buildWithdrawBody();
26
+
27
+ await sendTransaction(agent, [
28
+ internal({
29
+ to: Address.parse(addr),
30
+ value: toNano("0.02"),
31
+ bounce: true,
32
+ body,
33
+ }),
34
+ ]);
35
+
36
+ return {
37
+ withdrawn: true,
38
+ contractAddress: addr,
39
+ message: `Withdrawal sent to reputation contract ${addr.slice(0, 16)}...`,
40
+ };
41
+ } catch (err: any) {
42
+ return {
43
+ withdrawn: false,
44
+ error: err.message,
45
+ message: `Failed to withdraw: ${err.message}`,
46
+ };
47
+ }
48
+ },
49
+ });
50
+ }
51
+
52
+ export const withdrawReputationFeesAction = createWithdrawReputationFeesAction();