Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 107 additions & 0 deletions src/agent/tools/ton/__tests__/jetton-decimals.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { Address, type MessageRelaxed } from "@ton/core";
import { beforeEach, describe, expect, it, vi } from "vitest";

const mocks = vi.hoisted(() => ({
loadWallet: vi.fn(),
getCachedTonClient: vi.fn(),
openWallet: vi.fn(),
tonapiFetch: vi.fn(),
sendWalletTx: vi.fn(),
}));

vi.mock("../../../../ton/wallet-service.js", () => ({
loadWallet: mocks.loadWallet,
getCachedTonClient: mocks.getCachedTonClient,
}));
vi.mock("../../../../ton/wallet-open.js", () => ({ openWallet: mocks.openWallet }));
vi.mock("../../../../constants/api-endpoints.js", () => ({ tonapiFetch: mocks.tonapiFetch }));
vi.mock("../../../../ton/confirm.js", () => ({
sendWalletTx: mocks.sendWalletTx,
tonExplorerTxUrl: () => "https://example.invalid/transaction",
}));

import { jettonSendExecutor } from "../jetton-send.js";
import { jettonBalancesExecutor } from "../jetton-balances.js";

const owner = Address.parseRaw(`0:${"11".repeat(32)}`);
const master = Address.parseRaw(`0:${"22".repeat(32)}`);
const recipient = Address.parseRaw(`0:${"33".repeat(32)}`);
const jettonWallet = Address.parseRaw(`0:${"44".repeat(32)}`);
const context = {} as never;

function respondWithBalance(decimals: number | null | undefined, balance = "2000000000") {
mocks.tonapiFetch.mockResolvedValue(
new Response(
JSON.stringify({
balances: [
{
balance,
wallet_address: { address: jettonWallet.toString() },
jetton: { address: master.toString(), decimals, symbol: "TEST", name: "Test" },
},
],
})
)
);
}

beforeEach(() => {
vi.clearAllMocks();
mocks.loadWallet.mockReturnValue({ address: owner.toString() });
mocks.getCachedTonClient.mockResolvedValue({});
mocks.openWallet.mockResolvedValue({ keyPair: { secretKey: Buffer.alloc(64) }, contract: {} });
mocks.sendWalletTx.mockResolvedValue({ hash: "test-hash" });
});

describe("jetton decimal conversion", () => {
it.each([
{ decimals: 0, amount: 1, expected: 1n },
{ decimals: 9, amount: 1.25, expected: 1250000000n },
{ decimals: 6, amount: 1, expected: 1000000n },
{ decimals: undefined, amount: 1, expected: 1000000000n },
{ decimals: null, amount: 1, expected: 1000000000n },
])("encodes $amount tokens with decimals=$decimals as $expected units", async (test) => {
respondWithBalance(test.decimals);
const result = await jettonSendExecutor(
{ jetton_address: master.toString(), to: recipient.toString(), amount: test.amount },
context
);
expect(result.success).toBe(true);
expect(mocks.sendWalletTx).toHaveBeenCalledOnce();
const { messages } = mocks.sendWalletTx.mock.calls[0][2] as { messages: MessageRelaxed[] };
expect(messages[0].info.type).toBe("internal");
if (messages[0].info.type === "internal") {
expect(messages[0].info.dest.equals(jettonWallet)).toBe(true);
}
const body = messages[0].body.beginParse();
expect(body.loadUint(32)).toBe(0xf8a7ea5);
expect(body.loadUintBig(64)).toBe(0n);
expect(body.loadCoins()).toBe(test.expected);
expect(body.loadAddress().equals(recipient)).toBe(true);
});

it("rejects insufficient zero-decimal balance before reaching the send boundary", async () => {
respondWithBalance(0, "2");
expect(
await jettonSendExecutor(
{ jetton_address: master.toString(), to: recipient.toString(), amount: 3 },
context
)
).toMatchObject({ success: false });
expect(mocks.sendWalletTx).not.toHaveBeenCalled();
});

it.each([
{ decimals: 0, raw: "1234567890", expected: "1234567890", scale: 0 },
{ decimals: 9, raw: "1234000000", expected: "1.234", scale: 9 },
{ decimals: undefined, raw: "1234000000", expected: "1.234", scale: 9 },
{ decimals: null, raw: "1234000000", expected: "1.234", scale: 9 },
])("displays a balance with decimals=$decimals at its actual scale", async (test) => {
respondWithBalance(test.decimals, test.raw);
const result = await jettonBalancesExecutor({}, context);
expect(result).toMatchObject({
success: true,
data: { balances: [{ balance: test.expected, rawBalance: test.raw, decimals: test.scale }] },
});
});
});
2 changes: 1 addition & 1 deletion src/agent/tools/ton/jetton-balances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export const jettonBalancesExecutor: ToolExecutor<JettonBalancesParams> = async
}

// Convert balance from blockchain units to human-readable
const decimals = jetton.decimals || 9;
const decimals = jetton.decimals ?? 9;
const rawBalance = BigInt(balance);
const divisor = BigInt(10 ** decimals);
const wholePart = rawBalance / divisor;
Expand Down
2 changes: 1 addition & 1 deletion src/agent/tools/ton/jetton-send.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ export const jettonSendExecutor: ToolExecutor<JettonSendParams> = async (
}

const senderJettonWallet = jettonBalance.wallet_address.address;
const decimals = jettonBalance.jetton.decimals || 9;
const decimals = jettonBalance.jetton.decimals ?? 9;
const symbol = jettonBalance.jetton.symbol || "JETTON";
const currentBalance = BigInt(jettonBalance.balance);

Expand Down
156 changes: 156 additions & 0 deletions src/agent/tools/workspace/__tests__/mutations.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import {
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";

vi.mock("../../../../workspace/paths.js", async (importOriginal) => {
const original = await importOriginal<typeof import("../../../../workspace/paths.js")>();
return {
...original,
WORKSPACE_ROOT: mkdtempSync(join(tmpdir(), "teleton-mutations-")),
};
});

import { PROTECTED_WORKSPACE_FILES, WORKSPACE_ROOT } from "../../../../workspace/paths.js";
import { validateWritePath } from "../../../../workspace/validator.js";
import { workspaceDeleteExecutor } from "../delete.js";
import { workspaceRenameExecutor } from "../rename.js";

const context = {} as never;
const policyFiles = ["SOUL.md", "STRATEGY.md", "SECURITY.md"];

beforeEach(() => {
rmSync(WORKSPACE_ROOT, { recursive: true, force: true });
mkdirSync(WORKSPACE_ROOT);
for (const filename of PROTECTED_WORKSPACE_FILES) {
writeFileSync(join(WORKSPACE_ROOT, filename), `original ${filename}`);
}
writeFileSync(join(WORKSPACE_ROOT, "replacement.txt"), "replacement");
});

afterAll(() => rmSync(WORKSPACE_ROOT, { recursive: true, force: true }));

describe("workspace policy-file mutations", () => {
it.each(policyFiles)("rejects renaming %s away without changing files", async (filename) => {
await expect(
workspaceRenameExecutor({ from: filename, to: "moved.txt" }, context)
).rejects.toThrow("Cannot rename");
expect(readFileSync(join(WORKSPACE_ROOT, filename), "utf8")).toBe(`original ${filename}`);
expect(existsSync(join(WORKSPACE_ROOT, "moved.txt"))).toBe(false);
});

it.each(policyFiles)("rejects replacing %s without changing either file", async (filename) => {
await expect(
workspaceRenameExecutor({ from: "replacement.txt", to: filename, overwrite: true }, context)
).rejects.toThrow("Cannot rename");
expect(readFileSync(join(WORKSPACE_ROOT, filename), "utf8")).toBe(`original ${filename}`);
expect(readFileSync(join(WORKSPACE_ROOT, "replacement.txt"), "utf8")).toBe("replacement");
});

it.each(["./SECURITY.md", "folder/../SECURITY.md", "%2553ECURITY.md", "security.md"])(
"rejects normalized or case aliases: %s",
async (filename) => {
expect(() => validateWritePath(filename)).toThrow("Cannot write");
await expect(
workspaceRenameExecutor({ from: "replacement.txt", to: filename, overwrite: true }, context)
).rejects.toThrow("Cannot rename");
expect(readFileSync(join(WORKSPACE_ROOT, "SECURITY.md"), "utf8")).toBe(
"original SECURITY.md"
);
}
);

it("rejects creating an immutable destination before creating its parents", async () => {
await expect(
workspaceRenameExecutor({ from: "replacement.txt", to: "new/SOUL.md" }, context)
).rejects.toThrow("Cannot rename");
expect(existsSync(join(WORKSPACE_ROOT, "new"))).toBe(false);
expect(existsSync(join(WORKSPACE_ROOT, "replacement.txt"))).toBe(true);
});

it("preserves ordinary move, parent creation and overwrite behavior", async () => {
expect(
await workspaceRenameExecutor({ from: "replacement.txt", to: "new/file.txt" }, context)
).toMatchObject({ success: true });
writeFileSync(join(WORKSPACE_ROOT, "second.txt"), "second");
expect(
await workspaceRenameExecutor({ from: "second.txt", to: "new/file.txt" }, context)
).toMatchObject({ success: false });
expect(
await workspaceRenameExecutor(
{ from: "second.txt", to: "new/file.txt", overwrite: true },
context
)
).toMatchObject({ success: true });
expect(readFileSync(join(WORKSPACE_ROOT, "new/file.txt"), "utf8")).toBe("second");
});

it.each(PROTECTED_WORKSPACE_FILES)(
"preserves direct delete protection for %s",
async (filename) => {
expect(await workspaceDeleteExecutor({ path: filename }, context)).toMatchObject({
success: false,
});
expect(readFileSync(join(WORKSPACE_ROOT, filename), "utf8")).toBe(`original ${filename}`);
}
);

it.each([".", "folder/..", "%2e", WORKSPACE_ROOT])(
"rejects deleting the workspace root via %s",
async (path) => {
expect(await workspaceDeleteExecutor({ path, recursive: true }, context)).toMatchObject({
success: false,
});
expect(readFileSync(join(WORKSPACE_ROOT, "SECURITY.md"), "utf8")).toBe(
"original SECURITY.md"
);
expect(existsSync(join(WORKSPACE_ROOT, "replacement.txt"))).toBe(true);
}
);

it.each(["SECURITY.md", "soul.md", "MEMORY.md"])(
"rejects recursive deletion of a tree containing %s before removing ordinary files",
async (filename) => {
mkdirSync(join(WORKSPACE_ROOT, "nested/deep"), { recursive: true });
writeFileSync(join(WORKSPACE_ROOT, "nested/ordinary.txt"), "keep");
writeFileSync(join(WORKSPACE_ROOT, "nested/deep", filename), "protected");
expect(
await workspaceDeleteExecutor({ path: "nested", recursive: true }, context)
).toMatchObject({ success: false });
expect(readFileSync(join(WORKSPACE_ROOT, "nested/ordinary.txt"), "utf8")).toBe("keep");
expect(readFileSync(join(WORKSPACE_ROOT, "nested/deep", filename), "utf8")).toBe("protected");
}
);

it("deletes ordinary files and directories without following descendant symlinks", async () => {
const outside = mkdtempSync(join(tmpdir(), "teleton-mutations-outside-"));
try {
writeFileSync(join(outside, "SECURITY.md"), "outside");
mkdirSync(join(WORKSPACE_ROOT, "ordinary/deep"), { recursive: true });
writeFileSync(join(WORKSPACE_ROOT, "ordinary/deep/file.txt"), "remove");
symlinkSync(outside, join(WORKSPACE_ROOT, "ordinary/link"));
expect(
await workspaceDeleteExecutor({ path: "ordinary", recursive: true }, context)
).toMatchObject({ success: true });
expect(existsSync(join(WORKSPACE_ROOT, "ordinary"))).toBe(false);
expect(readFileSync(join(outside, "SECURITY.md"), "utf8")).toBe("outside");
expect(await workspaceDeleteExecutor({ path: "replacement.txt" }, context)).toMatchObject({
success: true,
});
mkdirSync(join(WORKSPACE_ROOT, "empty"));
expect(await workspaceDeleteExecutor({ path: "empty" }, context)).toMatchObject({
success: true,
});
} finally {
rmSync(outside, { recursive: true, force: true });
}
});
});
22 changes: 13 additions & 9 deletions src/agent/tools/workspace/delete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@
import { Type } from "@sinclair/typebox";
import { unlinkSync, rmdirSync, readdirSync, rmSync } from "fs";
import type { Tool, ToolExecutor } from "../types.js";
import { validatePath, PROTECTED_WORKSPACE_FILES } from "../../../workspace/index.js";
import {
assertDeletablePath,
validatePath,
WorkspaceSecurityError,
} from "../../../workspace/index.js";

interface WorkspaceDeleteParams {
path: string;
Expand Down Expand Up @@ -33,14 +37,14 @@ export const workspaceDeleteExecutor: ToolExecutor<WorkspaceDeleteParams> = asyn
// Validate the path
const validated = validatePath(path, false);

// Check if it's a protected file
if (PROTECTED_WORKSPACE_FILES.includes(validated.filename)) {
return {
success: false,
error:
`Cannot delete protected file: ${validated.filename}. ` +
`This file is essential for the agent's operation.`,
};
// Check the entire target before removing any part of a directory tree.
try {
assertDeletablePath(validated, path, recursive);
} catch (error) {
if (error instanceof WorkspaceSecurityError) {
return { success: false, error: error.message };
}
throw error;
}

if (validated.isDirectory) {
Expand Down
4 changes: 3 additions & 1 deletion src/agent/tools/workspace/rename.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { renameSync, existsSync } from "fs";
import { dirname } from "path";
import { mkdirSync } from "fs";
import type { Tool, ToolExecutor } from "../types.js";
import { validatePath } from "../../../workspace/index.js";
import { assertMutablePath, validatePath } from "../../../workspace/index.js";

interface WorkspaceRenameParams {
from: string;
Expand Down Expand Up @@ -38,6 +38,7 @@ export const workspaceRenameExecutor: ToolExecutor<WorkspaceRenameParams> = asyn

// Validate source path (must exist)
const validatedFrom = validatePath(from, false);
assertMutablePath(validatedFrom, from, "rename");

if (validatedFrom.isDirectory) {
return {
Expand All @@ -48,6 +49,7 @@ export const workspaceRenameExecutor: ToolExecutor<WorkspaceRenameParams> = asyn

// Validate destination path (may not exist yet)
const validatedTo = validatePath(to, true);
assertMutablePath(validatedTo, to, "rename");

// Check if destination already exists
if (validatedTo.exists && !overwrite) {
Expand Down
8 changes: 8 additions & 0 deletions src/workspace/__tests__/validator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ vi.mock("../paths.js", async () => {
WORKSPACE_ROOT: tempWorkspace,
TELETON_ROOT: join(tempWorkspace, ".."),
WORKSPACE_PATHS: {},
PROTECTED_WORKSPACE_FILES: [
"SOUL.md",
"STRATEGY.md",
"SECURITY.md",
"MEMORY.md",
"IDENTITY.md",
"USER.md",
],
ALLOWED_EXTENSIONS: {
images: [".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp"],
audio: [".mp3", ".ogg", ".wav", ".m4a", ".opus"],
Expand Down
2 changes: 2 additions & 0 deletions src/workspace/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ export {
validatePath,
validateReadPath,
validateWritePath,
assertMutablePath,
assertDeletablePath,
validateDirectory,
isWithinWorkspace,
sanitizeFilename,
Expand Down
Loading
Loading