@agent-native/core 0.7.49 → 0.7.51
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/a2a/agent-card.d.ts.map +1 -1
- package/dist/a2a/agent-card.js +21 -16
- package/dist/a2a/agent-card.js.map +1 -1
- package/dist/a2a/auth-policy.d.ts +10 -0
- package/dist/a2a/auth-policy.d.ts.map +1 -0
- package/dist/a2a/auth-policy.js +34 -0
- package/dist/a2a/auth-policy.js.map +1 -0
- package/dist/a2a/client.d.ts +6 -2
- package/dist/a2a/client.d.ts.map +1 -1
- package/dist/a2a/client.js +9 -4
- package/dist/a2a/client.js.map +1 -1
- package/dist/a2a/handlers.d.ts.map +1 -1
- package/dist/a2a/handlers.js +5 -4
- package/dist/a2a/handlers.js.map +1 -1
- package/dist/a2a/index.d.ts +1 -0
- package/dist/a2a/index.d.ts.map +1 -1
- package/dist/a2a/index.js +1 -0
- package/dist/a2a/index.js.map +1 -1
- package/dist/a2a/response-text.d.ts +4 -1
- package/dist/a2a/response-text.d.ts.map +1 -1
- package/dist/a2a/response-text.js +3 -2
- package/dist/a2a/response-text.js.map +1 -1
- package/dist/a2a/server.d.ts.map +1 -1
- package/dist/a2a/server.js +44 -29
- package/dist/a2a/server.js.map +1 -1
- package/dist/client/resources/ResourceEditor.d.ts.map +1 -1
- package/dist/client/resources/ResourceEditor.js +2 -4
- package/dist/client/resources/ResourceEditor.js.map +1 -1
- package/dist/client/settings/AgentsSection.d.ts.map +1 -1
- package/dist/client/settings/AgentsSection.js +4 -6
- package/dist/client/settings/AgentsSection.js.map +1 -1
- package/dist/deploy/build.d.ts.map +1 -1
- package/dist/deploy/build.js +8 -0
- package/dist/deploy/build.js.map +1 -1
- package/dist/deploy/route-discovery.d.ts.map +1 -1
- package/dist/deploy/route-discovery.js +11 -2
- package/dist/deploy/route-discovery.js.map +1 -1
- package/dist/integrations/a2a-continuation-processor.d.ts.map +1 -1
- package/dist/integrations/a2a-continuation-processor.js +39 -13
- package/dist/integrations/a2a-continuation-processor.js.map +1 -1
- package/dist/integrations/a2a-continuations-store.d.ts +2 -1
- package/dist/integrations/a2a-continuations-store.d.ts.map +1 -1
- package/dist/integrations/a2a-continuations-store.js +33 -4
- package/dist/integrations/a2a-continuations-store.js.map +1 -1
- package/dist/integrations/webhook-handler.js +4 -3
- package/dist/integrations/webhook-handler.js.map +1 -1
- package/dist/resources/handlers.d.ts.map +1 -1
- package/dist/resources/handlers.js +2 -3
- package/dist/resources/handlers.js.map +1 -1
- package/dist/resources/metadata.d.ts +5 -0
- package/dist/resources/metadata.d.ts.map +1 -1
- package/dist/resources/metadata.js +17 -2
- package/dist/resources/metadata.js.map +1 -1
- package/dist/resources/store.d.ts.map +1 -1
- package/dist/resources/store.js +2 -1
- package/dist/resources/store.js.map +1 -1
- package/dist/scripts/call-agent.d.ts.map +1 -1
- package/dist/scripts/call-agent.js +9 -4
- package/dist/scripts/call-agent.js.map +1 -1
- package/dist/server/agent-discovery.d.ts.map +1 -1
- package/dist/server/agent-discovery.js +7 -4
- package/dist/server/agent-discovery.js.map +1 -1
- package/dist/server/auth.d.ts.map +1 -1
- package/dist/server/auth.js +6 -0
- package/dist/server/auth.js.map +1 -1
- package/dist/vite/index.d.ts +1 -1
- package/dist/vite/index.d.ts.map +1 -1
- package/dist/vite/index.js +1 -1
- package/dist/vite/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/resources/store.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,UAAU,EACV,OAAO,EACP,cAAc,GAEf,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAEtE,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,MAAM,CAAC,MAAM,YAAY,GAAG,YAAY,CAAC;AAuBzC,IAAI,YAAuC,CAAC;AA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":["import {\n getDbExec,\n isPostgres,\n intType,\n retryOnDdlRace,\n type DbExec,\n} from \"../db/client.js\";\nimport { emitResourceChange, emitResourceDelete } from \"./emitter.js\";\nimport type { StoreWriteOptions } from \"../settings/store.js\";\nimport crypto from \"crypto\";\n\nexport const SHARED_OWNER = \"__shared__\";\n\nexport interface Resource {\n id: string;\n path: string;\n owner: string;\n content: string;\n mimeType: string;\n size: number;\n createdAt: number;\n updatedAt: number;\n}\n\nexport interface ResourceMeta {\n id: string;\n path: string;\n owner: string;\n mimeType: string;\n size: number;\n createdAt: number;\n updatedAt: number;\n}\n\nlet _initPromise: Promise<void> | undefined;\n\nconst DEFAULT_LEARNINGS_SHARED_MD = `# Learnings\n\nUser preferences, corrections, and patterns. The agent reads this at the start of every conversation.\n\nKeep this file tidy — revise, consolidate, and remove outdated entries. Don't just append forever.\n\n## Preferences\n\n## Corrections\n\n## Patterns\n`;\n\nconst DEFAULT_LEARNINGS_PERSONAL_MD = `# My Learnings\n\nPersonal preferences, corrections, and patterns — only visible to you.\n\n## Preferences\n\n## Corrections\n\n## Patterns\n`;\n\nconst DEFAULT_SKILL_LEARN_MD = `---\nname: learn\ndescription: >-\n Review the conversation and save structured memories for future sessions.\nuser-invocable: true\n---\n\n# Learn\n\nReview the current conversation and save anything worth remembering using the structured memory system.\n\n## Memory types\n\n- **user** — Preferences, role, personal context, contacts\n- **feedback** — Corrections (\"don't do X, do Y instead\"), confirmed approaches\n- **project** — Ongoing work context, decisions, status\n- **reference** — Pointers to external systems, URLs, API details\n\n## Steps\n\n1. Review the conversation for new insights\n2. Check your memory index: \\`resource-read --path memory/MEMORY.md\\`\n3. For each new insight, use \\`save-memory\\` with a descriptive name, type, and content\n4. If updating an existing memory, read it first with \\`resource-read --path memory/<name>.md\\`, then save with merged content\n\n## What NOT to capture\n\n- Things obvious from reading the code\n- Standard language/framework behavior\n- Temporary debugging notes\n- Anything already in AGENTS.md or other skills\n\nKeep one memory per logical topic. Descriptions should be concise — the index is loaded every conversation.\n`;\n\nconst DEFAULT_SKILL_LEARN_SHARED_MD = `---\nname: learn-shared\ndescription: >-\n Update the shared LEARNINGS.md with team-wide preferences, corrections, and\n patterns from this session.\nuser-invocable: true\n---\n\n# Learn (Shared)\n\nReview the current conversation and update the shared \\`LEARNINGS.md\\` resource with anything the whole team should know.\n\n## What to capture\n\n- **Team conventions** — agreed-upon approaches, code style decisions\n- **Technical learnings** — API quirks, library gotchas, surprising behavior\n- **Architectural decisions** — why something is done a certain way\n- **Corrections** — mistakes that any team member's agent should avoid\n\n## What NOT to capture\n\n- Personal preferences (use \\`/learn\\` for those)\n- Things obvious from reading the code\n- Standard language/framework behavior\n\n## Steps\n\n1. Read shared learnings: \\`pnpm action resource-read --path LEARNINGS.md --scope shared\\`\n2. Review the conversation for team-relevant insights\n3. Merge new learnings with existing ones — don't duplicate, refine existing entries\n4. Write back: \\`pnpm action resource-write --path LEARNINGS.md --scope shared --content \"...\"\\`\n\nKeep entries concise — one line per learning, grouped by category (Conventions, Technical, Patterns).\n`;\n\nconst DEFAULT_AGENTS_SHARED_MD = `# Agent Instructions\n\nThis file customizes how the AI agent behaves in this app. Edit it to add your own instructions, preferences, and context.\n\n## What to put here\n\n- **Preferences** — Tone, style, verbosity, response format\n- **Context** — Domain knowledge, terminology, team conventions\n- **Rules** — Things the agent should always/never do\n- **Skills** — Reference skill files for specialized tasks (create them in the \\`skills/\\` folder)\n\n## Skills\n\nYou can create skill files to give the agent specialized knowledge for specific tasks. Create resources under \\`skills/\\` (e.g., \\`skills/data-analysis.md\\`, \\`skills/code-review.md\\`) and reference them here:\n\n| Skill | Path | Description |\n|-------|------|-------------|\n| *(add your skills here)* | \\`skills/example.md\\` | What this skill teaches the agent |\n\nThe agent will read the relevant skill file when performing that type of task.\n\n## Example\n\n\\`\\`\\`markdown\n## Tone\nBe concise. Lead with the answer. Skip filler.\n\n## Code style\n- Use TypeScript, never JavaScript\n- Prefer named exports\n- Use early returns\n\n## Domain context\nWe sell B2B SaaS. Our customers are enterprise engineering teams.\n\\`\\`\\`\n`;\n\nconst DEFAULT_AGENTS_PERSONAL_MD = `# My Agent Instructions\n\nPersonal agent instructions — only visible to you. Use this for your own contacts, preferences, and context.\n\n## Contacts\n\nAdd people you frequently interact with so the agent can resolve names like \"email my wife\" or \"message John\":\n\n| Name | Email | Notes |\n|------|-------|-------|\n| *(add your contacts here)* | | |\n\n## Preferences\n\n## Context\n`;\n\nasync function ensureTable(): Promise<void> {\n if (!_initPromise) {\n _initPromise = _doEnsureTable().catch((err) => {\n // Don't cache the rejection — let the next caller retry a fresh init.\n _initPromise = undefined;\n throw err;\n });\n }\n return _initPromise;\n}\n\nasync function _doEnsureTable(): Promise<void> {\n const client = getDbExec();\n await retryOnDdlRace(() =>\n client.execute(`\n CREATE TABLE IF NOT EXISTS resources (\n id TEXT PRIMARY KEY,\n path TEXT NOT NULL,\n owner TEXT NOT NULL,\n content TEXT NOT NULL DEFAULT '',\n mime_type TEXT NOT NULL DEFAULT 'text/markdown',\n size ${intType()} NOT NULL DEFAULT 0,\n created_at ${intType()} NOT NULL,\n updated_at ${intType()} NOT NULL,\n UNIQUE(path, owner)\n )\n `),\n );\n\n // Seed default shared resources if they don't exist (INSERT OR IGNORE to avoid race conditions)\n const now = Date.now();\n const seedSql = isPostgres()\n ? `INSERT INTO resources (id, path, owner, content, mime_type, size, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (path, owner) DO NOTHING`\n : `INSERT OR IGNORE INTO resources (id, path, owner, content, mime_type, size, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`;\n\n // AGENTS.md — shared agent instructions\n const agentsSize = Buffer.byteLength(DEFAULT_AGENTS_SHARED_MD, \"utf8\");\n await client.execute({\n sql: seedSql,\n args: [\n crypto.randomUUID(),\n \"AGENTS.md\",\n SHARED_OWNER,\n DEFAULT_AGENTS_SHARED_MD,\n \"text/markdown\",\n agentsSize,\n now,\n now,\n ],\n });\n\n // LEARNINGS.md — shared learnings (preferences, corrections, patterns)\n const learningsSize = Buffer.byteLength(DEFAULT_LEARNINGS_SHARED_MD, \"utf8\");\n await client.execute({\n sql: seedSql,\n args: [\n crypto.randomUUID(),\n \"LEARNINGS.md\",\n SHARED_OWNER,\n DEFAULT_LEARNINGS_SHARED_MD,\n \"text/markdown\",\n learningsSize,\n now,\n now,\n ],\n });\n\n // skills/learn-shared.md — shared skill for updating shared LEARNINGS.md\n const learnSharedSize = Buffer.byteLength(\n DEFAULT_SKILL_LEARN_SHARED_MD,\n \"utf8\",\n );\n await client.execute({\n sql: seedSql,\n args: [\n crypto.randomUUID(),\n \"skills/learn-shared.md\",\n SHARED_OWNER,\n DEFAULT_SKILL_LEARN_SHARED_MD,\n \"text/markdown\",\n learnSharedSize,\n now,\n now,\n ],\n });\n\n // Seed built-in agents as shared resources under remote-agents/. ALWAYS\n // use the production URL here, never the env-resolved devUrl. The seed\n // runs once per DB (ON CONFLICT DO NOTHING), so a localhost URL written\n // during a dev run sticks forever — including when that DB is later used\n // by a prod deploy and the override wins over the built-in's prod URL.\n // (Verified problem: `dispatch.agent-native.com` had every remote-agents\n // entry pointing at localhost from an early-seed run, breaking call-agent\n // outbound from Lambda for ~12h before this was caught.)\n try {\n const { getBuiltinAgents, BUILTIN_AGENTS_FOR_SEEDING } =\n await import(\"../server/agent-discovery.js\");\n void getBuiltinAgents; // referenced to keep type-only import alive\n const builtins = BUILTIN_AGENTS_FOR_SEEDING;\n for (const agent of builtins) {\n const agentJson = JSON.stringify(\n {\n id: agent.id,\n name: agent.name,\n description: agent.description,\n url: agent.url, // always prod\n color: agent.color,\n },\n null,\n 2,\n );\n const agentSize = Buffer.byteLength(agentJson, \"utf8\");\n await client.execute({\n sql: seedSql,\n args: [\n crypto.randomUUID(),\n `remote-agents/${agent.id}.json`,\n SHARED_OWNER,\n agentJson,\n \"application/json\",\n agentSize,\n now,\n now,\n ],\n });\n }\n } catch {\n // Agent discovery not available — skip seeding\n }\n\n // One-time migration: rename legacy agents/*.json (A2A manifests) to\n // remote-agents/*.json so they live in their own folder, separate from\n // custom agents (agents/*.md).\n try {\n const legacy = await client.execute({\n sql: `SELECT id, path FROM resources WHERE path LIKE ? AND path LIKE ?`,\n args: [\"agents/%\", \"%.json\"],\n });\n const rows = (legacy.rows ?? []) as Array<{ id: string; path: string }>;\n for (const row of rows) {\n const newPath = row.path.replace(/^agents\\//, \"remote-agents/\");\n try {\n await client.execute({\n sql: `UPDATE resources SET path = ?, updated_at = ? WHERE id = ?`,\n args: [newPath, Date.now(), row.id],\n });\n } catch {\n // Skip if destination path already exists (unique constraint) —\n // we'll leave the old row in place; it'll be ignored by readers.\n }\n }\n } catch {\n // Migration best-effort\n }\n}\n\nconst _personalSeeded = new Set<string>();\n\n/**\n * Seed personal AGENTS.md and LEARNINGS.md for a user if they don't exist.\n * Called when listing resources or from the agent chat plugin.\n */\nexport async function ensurePersonalDefaults(owner: string): Promise<void> {\n if (owner === SHARED_OWNER || _personalSeeded.has(owner)) return;\n _personalSeeded.add(owner);\n await ensureTable();\n\n const client = getDbExec();\n const now = Date.now();\n const seedSql = isPostgres()\n ? `INSERT INTO resources (id, path, owner, content, mime_type, size, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (path, owner) DO NOTHING`\n : `INSERT OR IGNORE INTO resources (id, path, owner, content, mime_type, size, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`;\n\n const agentsSize = Buffer.byteLength(DEFAULT_AGENTS_PERSONAL_MD, \"utf8\");\n await client.execute({\n sql: seedSql,\n args: [\n crypto.randomUUID(),\n \"AGENTS.md\",\n owner,\n DEFAULT_AGENTS_PERSONAL_MD,\n \"text/markdown\",\n agentsSize,\n now,\n now,\n ],\n });\n\n const learningsSize = Buffer.byteLength(\n DEFAULT_LEARNINGS_PERSONAL_MD,\n \"utf8\",\n );\n await client.execute({\n sql: seedSql,\n args: [\n crypto.randomUUID(),\n \"LEARNINGS.md\",\n owner,\n DEFAULT_LEARNINGS_PERSONAL_MD,\n \"text/markdown\",\n learningsSize,\n now,\n now,\n ],\n });\n\n // memory/MEMORY.md — personal structured memory index\n const memoryIndexContent = \"# Memory Index\\n\";\n const memoryIndexSize = Buffer.byteLength(memoryIndexContent, \"utf8\");\n await client.execute({\n sql: seedSql,\n args: [\n crypto.randomUUID(),\n \"memory/MEMORY.md\",\n owner,\n memoryIndexContent,\n \"text/markdown\",\n memoryIndexSize,\n now,\n now,\n ],\n });\n\n // skills/learn.md — personal skill for updating memory\n const learnSize = Buffer.byteLength(DEFAULT_SKILL_LEARN_MD, \"utf8\");\n await client.execute({\n sql: seedSql,\n args: [\n crypto.randomUUID(),\n \"skills/learn.md\",\n owner,\n DEFAULT_SKILL_LEARN_MD,\n \"text/markdown\",\n learnSize,\n now,\n now,\n ],\n });\n}\n\nfunction rowToResource(row: any): Resource {\n return {\n id: row.id as string,\n path: row.path as string,\n owner: row.owner as string,\n content: row.content as string,\n mimeType: row.mime_type as string,\n size: row.size as number,\n createdAt: row.created_at as number,\n updatedAt: row.updated_at as number,\n };\n}\n\nfunction rowToMeta(row: any): ResourceMeta {\n return {\n id: row.id as string,\n path: row.path as string,\n owner: row.owner as string,\n mimeType: row.mime_type as string,\n size: row.size as number,\n createdAt: row.created_at as number,\n updatedAt: row.updated_at as number,\n };\n}\n\nexport async function resourceGet(id: string): Promise<Resource | null> {\n await ensureTable();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT * FROM resources WHERE id = ?`,\n args: [id],\n });\n if (rows.length === 0) return null;\n return rowToResource(rows[0]);\n}\n\nexport async function resourceGetByPath(\n owner: string,\n path: string,\n): Promise<Resource | null> {\n await ensureTable();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT * FROM resources WHERE owner = ? AND path = ?`,\n args: [owner, path],\n });\n if (rows.length === 0) return null;\n return rowToResource(rows[0]);\n}\n\nexport async function resourcePut(\n owner: string,\n path: string,\n content: string,\n mimeType?: string,\n options?: StoreWriteOptions,\n): Promise<Resource> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const size = Buffer.byteLength(content, \"utf8\");\n const mime = mimeType || \"text/markdown\";\n\n // Check for existing resource to preserve ID on upsert\n const { rows: existing } = await client.execute({\n sql: `SELECT id, created_at FROM resources WHERE owner = ? AND path = ?`,\n args: [owner, path],\n });\n\n const id =\n existing.length > 0 ? (existing[0].id as string) : crypto.randomUUID();\n const createdAt =\n existing.length > 0 ? (existing[0].created_at as number) : now;\n\n await client.execute({\n sql: isPostgres()\n ? `INSERT INTO resources (id, path, owner, content, mime_type, size, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (path, owner) DO UPDATE SET id=EXCLUDED.id, content=EXCLUDED.content, mime_type=EXCLUDED.mime_type, size=EXCLUDED.size, updated_at=EXCLUDED.updated_at`\n : `INSERT OR REPLACE INTO resources (id, path, owner, content, mime_type, size, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n args: [id, path, owner, content, mime, size, createdAt, now],\n });\n\n emitResourceChange(id, path, owner, options?.requestSource);\n\n return {\n id,\n path,\n owner,\n content,\n mimeType: mime,\n size,\n createdAt,\n updatedAt: now,\n };\n}\n\nexport async function resourceDelete(id: string): Promise<boolean> {\n await ensureTable();\n const client = getDbExec();\n\n // Get resource info for emitter before deleting\n const { rows } = await client.execute({\n sql: `SELECT path, owner FROM resources WHERE id = ?`,\n args: [id],\n });\n if (rows.length === 0) return false;\n\n const result = await client.execute({\n sql: `DELETE FROM resources WHERE id = ?`,\n args: [id],\n });\n const deleted = result.rowsAffected > 0;\n if (deleted) {\n emitResourceDelete(id, rows[0].path as string, rows[0].owner as string);\n }\n return deleted;\n}\n\nexport async function resourceDeleteByPath(\n owner: string,\n path: string,\n): Promise<boolean> {\n await ensureTable();\n const client = getDbExec();\n\n // Get resource info for emitter before deleting\n const { rows } = await client.execute({\n sql: `SELECT id FROM resources WHERE owner = ? AND path = ?`,\n args: [owner, path],\n });\n if (rows.length === 0) return false;\n\n const result = await client.execute({\n sql: `DELETE FROM resources WHERE owner = ? AND path = ?`,\n args: [owner, path],\n });\n const deleted = result.rowsAffected > 0;\n if (deleted) {\n emitResourceDelete(rows[0].id as string, path, owner);\n }\n return deleted;\n}\n\nexport async function resourceList(\n owner: string,\n pathPrefix?: string,\n): Promise<ResourceMeta[]> {\n await ensureTable();\n const client = getDbExec();\n\n if (pathPrefix) {\n const { rows } = await client.execute({\n sql: `SELECT id, path, owner, mime_type, size, created_at, updated_at FROM resources WHERE owner = ? AND path LIKE ?`,\n args: [owner, pathPrefix + \"%\"],\n });\n return rows.map(rowToMeta);\n }\n\n const { rows } = await client.execute({\n sql: `SELECT id, path, owner, mime_type, size, created_at, updated_at FROM resources WHERE owner = ?`,\n args: [owner],\n });\n return rows.map(rowToMeta);\n}\n\nexport async function resourceListAccessible(\n userEmail: string,\n pathPrefix?: string,\n): Promise<ResourceMeta[]> {\n await ensureTable();\n const client = getDbExec();\n\n if (pathPrefix) {\n const { rows } = await client.execute({\n sql: `SELECT id, path, owner, mime_type, size, created_at, updated_at FROM resources WHERE owner = ? AND path LIKE ?\n UNION\n SELECT id, path, owner, mime_type, size, created_at, updated_at FROM resources WHERE owner = ? AND path LIKE ?`,\n args: [userEmail, pathPrefix + \"%\", SHARED_OWNER, pathPrefix + \"%\"],\n });\n return rows.map(rowToMeta);\n }\n\n const { rows } = await client.execute({\n sql: `SELECT id, path, owner, mime_type, size, created_at, updated_at FROM resources WHERE owner = ?\n UNION\n SELECT id, path, owner, mime_type, size, created_at, updated_at FROM resources WHERE owner = ?`,\n args: [userEmail, SHARED_OWNER],\n });\n return rows.map(rowToMeta);\n}\n\n/**\n * List all resources matching a path prefix across ALL owners.\n * Used by the recurring jobs scheduler to find all job resources.\n */\nexport async function resourceListAllOwners(\n pathPrefix: string,\n): Promise<Resource[]> {\n await ensureTable();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT * FROM resources WHERE path LIKE ?`,\n args: [pathPrefix + \"%\"],\n });\n return rows.map(rowToResource);\n}\n\nexport async function resourceMove(\n id: string,\n newPath: string,\n): Promise<boolean> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n\n // Get current resource info\n const { rows } = await client.execute({\n sql: `SELECT path, owner FROM resources WHERE id = ?`,\n args: [id],\n });\n if (rows.length === 0) return false;\n\n const result = await client.execute({\n sql: `UPDATE resources SET path = ?, updated_at = ? WHERE id = ?`,\n args: [newPath, now, id],\n });\n const moved = result.rowsAffected > 0;\n if (moved) {\n emitResourceChange(id, newPath, rows[0].owner as string);\n }\n return moved;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/resources/store.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,UAAU,EACV,OAAO,EACP,cAAc,GAEf,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAEtE,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,MAAM,CAAC,MAAM,YAAY,GAAG,YAAY,CAAC;AAuBzC,IAAI,YAAuC,CAAC;AAE5C,MAAM,2BAA2B,GAAG;;;;;;;;;;;CAWnC,CAAC;AAEF,MAAM,6BAA6B,GAAG;;;;;;;;;CASrC,CAAC;AAEF,MAAM,sBAAsB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiC9B,CAAC;AAEF,MAAM,6BAA6B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiCrC,CAAC;AAEF,MAAM,wBAAwB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmChC,CAAC;AAEF,MAAM,0BAA0B,GAAG;;;;;;;;;;;;;;;CAelC,CAAC;AAEF,KAAK,UAAU,WAAW;IACxB,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,YAAY,GAAG,cAAc,EAAE,CAAC,KAAK,C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e;IAEf,MAAM,WAAW,EAAE,CAAC;IACpB,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IAEvB,4BAA4B;IAC5B,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC;QACpC,GAAG,EAAE,gDAAgD;QACrD,IAAI,EAAE,CAAC,EAAE,CAAC;KACX,CAAC,CAAC;IACH,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAEpC,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC;QAClC,GAAG,EAAE,4DAA4D;QACjE,IAAI,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,EAAE,CAAC;KACzB,CAAC,CAAC;IACH,MAAM,KAAK,GAAG,MAAM,CAAC,YAAY,GAAG,CAAC,CAAC;IACtC,IAAI,KAAK,EAAE,CAAC;QACV,kBAAkB,CAAC,EAAE,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,KAAe,CAAC,CAAC;IAC3D,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import {\n getDbExec,\n isPostgres,\n intType,\n retryOnDdlRace,\n type DbExec,\n} from \"../db/client.js\";\nimport { emitResourceChange, emitResourceDelete } from \"./emitter.js\";\nimport type { StoreWriteOptions } from \"../settings/store.js\";\nimport crypto from \"crypto\";\n\nexport const SHARED_OWNER = \"__shared__\";\n\nexport interface Resource {\n id: string;\n path: string;\n owner: string;\n content: string;\n mimeType: string;\n size: number;\n createdAt: number;\n updatedAt: number;\n}\n\nexport interface ResourceMeta {\n id: string;\n path: string;\n owner: string;\n mimeType: string;\n size: number;\n createdAt: number;\n updatedAt: number;\n}\n\nlet _initPromise: Promise<void> | undefined;\n\nconst DEFAULT_LEARNINGS_SHARED_MD = `# Learnings\n\nUser preferences, corrections, and patterns. The agent reads this at the start of every conversation.\n\nKeep this file tidy — revise, consolidate, and remove outdated entries. Don't just append forever.\n\n## Preferences\n\n## Corrections\n\n## Patterns\n`;\n\nconst DEFAULT_LEARNINGS_PERSONAL_MD = `# My Learnings\n\nPersonal preferences, corrections, and patterns — only visible to you.\n\n## Preferences\n\n## Corrections\n\n## Patterns\n`;\n\nconst DEFAULT_SKILL_LEARN_MD = `---\nname: learn\ndescription: >-\n Review the conversation and save structured memories for future sessions.\nuser-invocable: true\n---\n\n# Learn\n\nReview the current conversation and save anything worth remembering using the structured memory system.\n\n## Memory types\n\n- **user** — Preferences, role, personal context, contacts\n- **feedback** — Corrections (\"don't do X, do Y instead\"), confirmed approaches\n- **project** — Ongoing work context, decisions, status\n- **reference** — Pointers to external systems, URLs, API details\n\n## Steps\n\n1. Review the conversation for new insights\n2. Check your memory index: \\`resource-read --path memory/MEMORY.md\\`\n3. For each new insight, use \\`save-memory\\` with a descriptive name, type, and content\n4. If updating an existing memory, read it first with \\`resource-read --path memory/<name>.md\\`, then save with merged content\n\n## What NOT to capture\n\n- Things obvious from reading the code\n- Standard language/framework behavior\n- Temporary debugging notes\n- Anything already in AGENTS.md or other skills\n\nKeep one memory per logical topic. Descriptions should be concise — the index is loaded every conversation.\n`;\n\nconst DEFAULT_SKILL_LEARN_SHARED_MD = `---\nname: learn-shared\ndescription: >-\n Update the shared LEARNINGS.md with team-wide preferences, corrections, and\n patterns from this session.\nuser-invocable: true\n---\n\n# Learn (Shared)\n\nReview the current conversation and update the shared \\`LEARNINGS.md\\` resource with anything the whole team should know.\n\n## What to capture\n\n- **Team conventions** — agreed-upon approaches, code style decisions\n- **Technical learnings** — API quirks, library gotchas, surprising behavior\n- **Architectural decisions** — why something is done a certain way\n- **Corrections** — mistakes that any team member's agent should avoid\n\n## What NOT to capture\n\n- Personal preferences (use \\`/learn\\` for those)\n- Things obvious from reading the code\n- Standard language/framework behavior\n\n## Steps\n\n1. Read shared learnings: \\`pnpm action resource-read --path LEARNINGS.md --scope shared\\`\n2. Review the conversation for team-relevant insights\n3. Merge new learnings with existing ones — don't duplicate, refine existing entries\n4. Write back: \\`pnpm action resource-write --path LEARNINGS.md --scope shared --content \"...\"\\`\n\nKeep entries concise — one line per learning, grouped by category (Conventions, Technical, Patterns).\n`;\n\nconst DEFAULT_AGENTS_SHARED_MD = `# Agent Instructions\n\nThis file customizes how the AI agent behaves in this app. Edit it to add your own instructions, preferences, and context.\n\n## What to put here\n\n- **Preferences** — Tone, style, verbosity, response format\n- **Context** — Domain knowledge, terminology, team conventions\n- **Rules** — Things the agent should always/never do\n- **Skills** — Reference skill files for specialized tasks (create them in the \\`skills/\\` folder)\n\n## Skills\n\nYou can create skill files to give the agent specialized knowledge for specific tasks. Create resources under \\`skills/\\` (e.g., \\`skills/data-analysis.md\\`, \\`skills/code-review.md\\`) and reference them here:\n\n| Skill | Path | Description |\n|-------|------|-------------|\n| *(add your skills here)* | \\`skills/example.md\\` | What this skill teaches the agent |\n\nThe agent will read the relevant skill file when performing that type of task.\n\n## Example\n\n\\`\\`\\`markdown\n## Tone\nBe concise. Lead with the answer. Skip filler.\n\n## Code style\n- Use TypeScript, never JavaScript\n- Prefer named exports\n- Use early returns\n\n## Domain context\nWe sell B2B SaaS. Our customers are enterprise engineering teams.\n\\`\\`\\`\n`;\n\nconst DEFAULT_AGENTS_PERSONAL_MD = `# My Agent Instructions\n\nPersonal agent instructions — only visible to you. Use this for your own contacts, preferences, and context.\n\n## Contacts\n\nAdd people you frequently interact with so the agent can resolve names like \"email my wife\" or \"message John\":\n\n| Name | Email | Notes |\n|------|-------|-------|\n| *(add your contacts here)* | | |\n\n## Preferences\n\n## Context\n`;\n\nasync function ensureTable(): Promise<void> {\n if (!_initPromise) {\n _initPromise = _doEnsureTable().catch((err) => {\n // Don't cache the rejection — let the next caller retry a fresh init.\n _initPromise = undefined;\n throw err;\n });\n }\n return _initPromise;\n}\n\nasync function _doEnsureTable(): Promise<void> {\n const client = getDbExec();\n await retryOnDdlRace(() =>\n client.execute(`\n CREATE TABLE IF NOT EXISTS resources (\n id TEXT PRIMARY KEY,\n path TEXT NOT NULL,\n owner TEXT NOT NULL,\n content TEXT NOT NULL DEFAULT '',\n mime_type TEXT NOT NULL DEFAULT 'text/markdown',\n size ${intType()} NOT NULL DEFAULT 0,\n created_at ${intType()} NOT NULL,\n updated_at ${intType()} NOT NULL,\n UNIQUE(path, owner)\n )\n `),\n );\n\n // Seed default shared resources if they don't exist (INSERT OR IGNORE to avoid race conditions)\n const now = Date.now();\n const seedSql = isPostgres()\n ? `INSERT INTO resources (id, path, owner, content, mime_type, size, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (path, owner) DO NOTHING`\n : `INSERT OR IGNORE INTO resources (id, path, owner, content, mime_type, size, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`;\n\n // AGENTS.md — shared agent instructions\n const agentsSize = Buffer.byteLength(DEFAULT_AGENTS_SHARED_MD, \"utf8\");\n await client.execute({\n sql: seedSql,\n args: [\n crypto.randomUUID(),\n \"AGENTS.md\",\n SHARED_OWNER,\n DEFAULT_AGENTS_SHARED_MD,\n \"text/markdown\",\n agentsSize,\n now,\n now,\n ],\n });\n\n // LEARNINGS.md — shared learnings (preferences, corrections, patterns)\n const learningsSize = Buffer.byteLength(DEFAULT_LEARNINGS_SHARED_MD, \"utf8\");\n await client.execute({\n sql: seedSql,\n args: [\n crypto.randomUUID(),\n \"LEARNINGS.md\",\n SHARED_OWNER,\n DEFAULT_LEARNINGS_SHARED_MD,\n \"text/markdown\",\n learningsSize,\n now,\n now,\n ],\n });\n\n // skills/learn-shared.md — shared skill for updating shared LEARNINGS.md\n const learnSharedSize = Buffer.byteLength(\n DEFAULT_SKILL_LEARN_SHARED_MD,\n \"utf8\",\n );\n await client.execute({\n sql: seedSql,\n args: [\n crypto.randomUUID(),\n \"skills/learn-shared.md\",\n SHARED_OWNER,\n DEFAULT_SKILL_LEARN_SHARED_MD,\n \"text/markdown\",\n learnSharedSize,\n now,\n now,\n ],\n });\n\n // Seed built-in agents as shared resources under remote-agents/. ALWAYS\n // use the production URL here, never the env-resolved devUrl. The seed\n // runs once per DB (ON CONFLICT DO NOTHING), so a localhost URL written\n // during a dev run sticks forever — including when that DB is later used\n // by a prod deploy and the override wins over the built-in's prod URL.\n // (Verified problem: `dispatch.agent-native.com` had every remote-agents\n // entry pointing at localhost from an early-seed run, breaking call-agent\n // outbound from Lambda for ~12h before this was caught.)\n try {\n const { getBuiltinAgents, BUILTIN_AGENTS_FOR_SEEDING } =\n await import(\"../server/agent-discovery.js\");\n void getBuiltinAgents; // referenced to keep type-only import alive\n const builtins = BUILTIN_AGENTS_FOR_SEEDING;\n for (const agent of builtins) {\n const agentJson = JSON.stringify(\n {\n id: agent.id,\n name: agent.name,\n description: agent.description,\n url: agent.url, // always prod\n color: agent.color,\n },\n null,\n 2,\n );\n const agentSize = Buffer.byteLength(agentJson, \"utf8\");\n await client.execute({\n sql: seedSql,\n args: [\n crypto.randomUUID(),\n `remote-agents/${agent.id}.json`,\n SHARED_OWNER,\n agentJson,\n \"application/json\",\n agentSize,\n now,\n now,\n ],\n });\n }\n } catch {\n // Agent discovery not available — skip seeding\n }\n\n // One-time migration: rename legacy agents/*.json (A2A manifests) to\n // remote-agents/*.json so they live in their own folder, separate from\n // custom agents (agents/*.md).\n try {\n const legacy = await client.execute({\n sql: `SELECT id, path FROM resources WHERE path LIKE ? AND path LIKE ?`,\n args: [\"agents/%\", \"%.json\"],\n });\n const rows = (legacy.rows ?? []) as Array<{ id: string; path: string }>;\n for (const row of rows) {\n const newPath = row.path.replace(/^agents\\//, \"remote-agents/\");\n try {\n await client.execute({\n sql: `UPDATE resources SET path = ?, updated_at = ? WHERE id = ?`,\n args: [newPath, Date.now(), row.id],\n });\n } catch {\n // Skip if destination path already exists (unique constraint) —\n // we'll leave the old row in place; readers accept both paths and\n // canonical remote-agents/ entries win when both exist.\n }\n }\n } catch {\n // Migration best-effort\n }\n}\n\nconst _personalSeeded = new Set<string>();\n\n/**\n * Seed personal AGENTS.md and LEARNINGS.md for a user if they don't exist.\n * Called when listing resources or from the agent chat plugin.\n */\nexport async function ensurePersonalDefaults(owner: string): Promise<void> {\n if (owner === SHARED_OWNER || _personalSeeded.has(owner)) return;\n _personalSeeded.add(owner);\n await ensureTable();\n\n const client = getDbExec();\n const now = Date.now();\n const seedSql = isPostgres()\n ? `INSERT INTO resources (id, path, owner, content, mime_type, size, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (path, owner) DO NOTHING`\n : `INSERT OR IGNORE INTO resources (id, path, owner, content, mime_type, size, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`;\n\n const agentsSize = Buffer.byteLength(DEFAULT_AGENTS_PERSONAL_MD, \"utf8\");\n await client.execute({\n sql: seedSql,\n args: [\n crypto.randomUUID(),\n \"AGENTS.md\",\n owner,\n DEFAULT_AGENTS_PERSONAL_MD,\n \"text/markdown\",\n agentsSize,\n now,\n now,\n ],\n });\n\n const learningsSize = Buffer.byteLength(\n DEFAULT_LEARNINGS_PERSONAL_MD,\n \"utf8\",\n );\n await client.execute({\n sql: seedSql,\n args: [\n crypto.randomUUID(),\n \"LEARNINGS.md\",\n owner,\n DEFAULT_LEARNINGS_PERSONAL_MD,\n \"text/markdown\",\n learningsSize,\n now,\n now,\n ],\n });\n\n // memory/MEMORY.md — personal structured memory index\n const memoryIndexContent = \"# Memory Index\\n\";\n const memoryIndexSize = Buffer.byteLength(memoryIndexContent, \"utf8\");\n await client.execute({\n sql: seedSql,\n args: [\n crypto.randomUUID(),\n \"memory/MEMORY.md\",\n owner,\n memoryIndexContent,\n \"text/markdown\",\n memoryIndexSize,\n now,\n now,\n ],\n });\n\n // skills/learn.md — personal skill for updating memory\n const learnSize = Buffer.byteLength(DEFAULT_SKILL_LEARN_MD, \"utf8\");\n await client.execute({\n sql: seedSql,\n args: [\n crypto.randomUUID(),\n \"skills/learn.md\",\n owner,\n DEFAULT_SKILL_LEARN_MD,\n \"text/markdown\",\n learnSize,\n now,\n now,\n ],\n });\n}\n\nfunction rowToResource(row: any): Resource {\n return {\n id: row.id as string,\n path: row.path as string,\n owner: row.owner as string,\n content: row.content as string,\n mimeType: row.mime_type as string,\n size: row.size as number,\n createdAt: row.created_at as number,\n updatedAt: row.updated_at as number,\n };\n}\n\nfunction rowToMeta(row: any): ResourceMeta {\n return {\n id: row.id as string,\n path: row.path as string,\n owner: row.owner as string,\n mimeType: row.mime_type as string,\n size: row.size as number,\n createdAt: row.created_at as number,\n updatedAt: row.updated_at as number,\n };\n}\n\nexport async function resourceGet(id: string): Promise<Resource | null> {\n await ensureTable();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT * FROM resources WHERE id = ?`,\n args: [id],\n });\n if (rows.length === 0) return null;\n return rowToResource(rows[0]);\n}\n\nexport async function resourceGetByPath(\n owner: string,\n path: string,\n): Promise<Resource | null> {\n await ensureTable();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT * FROM resources WHERE owner = ? AND path = ?`,\n args: [owner, path],\n });\n if (rows.length === 0) return null;\n return rowToResource(rows[0]);\n}\n\nexport async function resourcePut(\n owner: string,\n path: string,\n content: string,\n mimeType?: string,\n options?: StoreWriteOptions,\n): Promise<Resource> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const size = Buffer.byteLength(content, \"utf8\");\n const mime = mimeType || \"text/markdown\";\n\n // Check for existing resource to preserve ID on upsert\n const { rows: existing } = await client.execute({\n sql: `SELECT id, created_at FROM resources WHERE owner = ? AND path = ?`,\n args: [owner, path],\n });\n\n const id =\n existing.length > 0 ? (existing[0].id as string) : crypto.randomUUID();\n const createdAt =\n existing.length > 0 ? (existing[0].created_at as number) : now;\n\n await client.execute({\n sql: isPostgres()\n ? `INSERT INTO resources (id, path, owner, content, mime_type, size, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (path, owner) DO UPDATE SET id=EXCLUDED.id, content=EXCLUDED.content, mime_type=EXCLUDED.mime_type, size=EXCLUDED.size, updated_at=EXCLUDED.updated_at`\n : `INSERT OR REPLACE INTO resources (id, path, owner, content, mime_type, size, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n args: [id, path, owner, content, mime, size, createdAt, now],\n });\n\n emitResourceChange(id, path, owner, options?.requestSource);\n\n return {\n id,\n path,\n owner,\n content,\n mimeType: mime,\n size,\n createdAt,\n updatedAt: now,\n };\n}\n\nexport async function resourceDelete(id: string): Promise<boolean> {\n await ensureTable();\n const client = getDbExec();\n\n // Get resource info for emitter before deleting\n const { rows } = await client.execute({\n sql: `SELECT path, owner FROM resources WHERE id = ?`,\n args: [id],\n });\n if (rows.length === 0) return false;\n\n const result = await client.execute({\n sql: `DELETE FROM resources WHERE id = ?`,\n args: [id],\n });\n const deleted = result.rowsAffected > 0;\n if (deleted) {\n emitResourceDelete(id, rows[0].path as string, rows[0].owner as string);\n }\n return deleted;\n}\n\nexport async function resourceDeleteByPath(\n owner: string,\n path: string,\n): Promise<boolean> {\n await ensureTable();\n const client = getDbExec();\n\n // Get resource info for emitter before deleting\n const { rows } = await client.execute({\n sql: `SELECT id FROM resources WHERE owner = ? AND path = ?`,\n args: [owner, path],\n });\n if (rows.length === 0) return false;\n\n const result = await client.execute({\n sql: `DELETE FROM resources WHERE owner = ? AND path = ?`,\n args: [owner, path],\n });\n const deleted = result.rowsAffected > 0;\n if (deleted) {\n emitResourceDelete(rows[0].id as string, path, owner);\n }\n return deleted;\n}\n\nexport async function resourceList(\n owner: string,\n pathPrefix?: string,\n): Promise<ResourceMeta[]> {\n await ensureTable();\n const client = getDbExec();\n\n if (pathPrefix) {\n const { rows } = await client.execute({\n sql: `SELECT id, path, owner, mime_type, size, created_at, updated_at FROM resources WHERE owner = ? AND path LIKE ?`,\n args: [owner, pathPrefix + \"%\"],\n });\n return rows.map(rowToMeta);\n }\n\n const { rows } = await client.execute({\n sql: `SELECT id, path, owner, mime_type, size, created_at, updated_at FROM resources WHERE owner = ?`,\n args: [owner],\n });\n return rows.map(rowToMeta);\n}\n\nexport async function resourceListAccessible(\n userEmail: string,\n pathPrefix?: string,\n): Promise<ResourceMeta[]> {\n await ensureTable();\n const client = getDbExec();\n\n if (pathPrefix) {\n const { rows } = await client.execute({\n sql: `SELECT id, path, owner, mime_type, size, created_at, updated_at FROM resources WHERE owner = ? AND path LIKE ?\n UNION\n SELECT id, path, owner, mime_type, size, created_at, updated_at FROM resources WHERE owner = ? AND path LIKE ?`,\n args: [userEmail, pathPrefix + \"%\", SHARED_OWNER, pathPrefix + \"%\"],\n });\n return rows.map(rowToMeta);\n }\n\n const { rows } = await client.execute({\n sql: `SELECT id, path, owner, mime_type, size, created_at, updated_at FROM resources WHERE owner = ?\n UNION\n SELECT id, path, owner, mime_type, size, created_at, updated_at FROM resources WHERE owner = ?`,\n args: [userEmail, SHARED_OWNER],\n });\n return rows.map(rowToMeta);\n}\n\n/**\n * List all resources matching a path prefix across ALL owners.\n * Used by the recurring jobs scheduler to find all job resources.\n */\nexport async function resourceListAllOwners(\n pathPrefix: string,\n): Promise<Resource[]> {\n await ensureTable();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT * FROM resources WHERE path LIKE ?`,\n args: [pathPrefix + \"%\"],\n });\n return rows.map(rowToResource);\n}\n\nexport async function resourceMove(\n id: string,\n newPath: string,\n): Promise<boolean> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n\n // Get current resource info\n const { rows } = await client.execute({\n sql: `SELECT path, owner FROM resources WHERE id = ?`,\n args: [id],\n });\n if (rows.length === 0) return false;\n\n const result = await client.execute({\n sql: `UPDATE resources SET path = ?, updated_at = ? WHERE id = ?`,\n args: [newPath, now, id],\n });\n const moved = result.rowsAffected > 0;\n if (moved) {\n emitResourceChange(id, newPath, rows[0].owner as string);\n }\n return moved;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"call-agent.d.ts","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAuDrE,eAAO,MAAM,IAAI,EAAE,UAqBlB,CAAC;AAEF,wBAAsB,GAAG,CACvB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAC5B,OAAO,CAAC,EAAE,gBAAgB,EAC1B,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC,
|
|
1
|
+
{"version":3,"file":"call-agent.d.ts","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAuDrE,eAAO,MAAM,IAAI,EAAE,UAqBlB,CAAC;AAEF,wBAAsB,GAAG,CACvB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAC5B,OAAO,CAAC,EAAE,gBAAgB,EAC1B,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC,CAwMjB;AAkDD,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CASzE"}
|
|
@@ -113,7 +113,10 @@ export async function run(args, context, selfAppId) {
|
|
|
113
113
|
let apiKey;
|
|
114
114
|
if (callerEmail && (callerOrgSecret || process.env.A2A_SECRET)) {
|
|
115
115
|
try {
|
|
116
|
-
apiKey = await signA2AToken(callerEmail, callerOrgDomain, callerOrgSecret, {
|
|
116
|
+
apiKey = await signA2AToken(callerEmail, callerOrgDomain, callerOrgSecret, {
|
|
117
|
+
expiresIn: INTEGRATION_A2A_TOKEN_TTL,
|
|
118
|
+
preferGlobalSecret: true,
|
|
119
|
+
});
|
|
117
120
|
}
|
|
118
121
|
catch { }
|
|
119
122
|
}
|
|
@@ -183,7 +186,7 @@ export async function run(args, context, selfAppId) {
|
|
|
183
186
|
}
|
|
184
187
|
catch (pollErr) {
|
|
185
188
|
if (pollErr instanceof A2ATaskTimeoutError) {
|
|
186
|
-
const queued = await enqueueIntegrationContinuationIfPossible(pollErr, agent, callerEmail
|
|
189
|
+
const queued = await enqueueIntegrationContinuationIfPossible(pollErr, agent, callerEmail);
|
|
187
190
|
if (queued) {
|
|
188
191
|
responseText = `${A2A_CONTINUATION_QUEUED_MARKER}\nThe ${agent.name} agent is still working. Do not send an interim reply to the user; the final result will be posted to the originating integration thread automatically.`;
|
|
189
192
|
}
|
|
@@ -237,7 +240,7 @@ export async function run(args, context, selfAppId) {
|
|
|
237
240
|
return `Error calling ${agent.name}: ${msg}`;
|
|
238
241
|
}
|
|
239
242
|
}
|
|
240
|
-
async function enqueueIntegrationContinuationIfPossible(error, agent, ownerEmail
|
|
243
|
+
async function enqueueIntegrationContinuationIfPossible(error, agent, ownerEmail) {
|
|
241
244
|
const integration = getIntegrationRequestContext();
|
|
242
245
|
if (!integration || !ownerEmail)
|
|
243
246
|
return false;
|
|
@@ -257,7 +260,9 @@ async function enqueueIntegrationContinuationIfPossible(error, agent, ownerEmail
|
|
|
257
260
|
agentName: agent.name,
|
|
258
261
|
agentUrl: agent.url,
|
|
259
262
|
a2aTaskId: error.taskId,
|
|
260
|
-
|
|
263
|
+
// Do not persist the short-lived JWT used for the initial send. The
|
|
264
|
+
// continuation processor can mint a fresh token for each poll.
|
|
265
|
+
a2aAuthToken: null,
|
|
261
266
|
});
|
|
262
267
|
await dispatchA2AContinuation(continuation.id).catch((err) => {
|
|
263
268
|
console.error(`[call-agent] Failed to dispatch A2A continuation ${continuation.id}:`, err);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"call-agent.js","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAEA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ACvB,YAAY,EAAE,YAAY,IAAI,EAAE;SACjC,CAAC,CAAC;QACH,MAAM,uBAAuB,CAAC,YAAY,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;YAC3D,OAAO,CAAC,KAAK,CACX,oDAAoD,YAAY,CAAC,EAAE,GAAG,EACtE,GAAG,CACJ,CAAC;QACJ,CAAC,CAAC,CAAC;QACH,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,kDAAkD,EAAE,GAAG,CAAC,CAAC;QACvE,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED,+EAA+E;AAC/E,8EAA8E;AAC9E,6EAA6E;AAC7E,2EAA2E;AAC3E,4EAA4E;AAC5E,4CAA4C;AAC5C,MAAM,UAAU,kBAAkB,CAAC,IAAY,EAAE,QAAgB;IAC/D,IAAI,CAAC,IAAI,IAAI,CAAC,QAAQ;QAAE,OAAO,IAAI,CAAC;IACpC,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IACzC,4EAA4E;IAC5E,8EAA8E;IAC9E,OAAO,IAAI,CAAC,OAAO,CACjB,qDAAqD,EACrD,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,EAAE,CAChD,CAAC;AACJ,CAAC","sourcesContent":["import type { ActionTool } from \"../agent/types.js\";\nimport type { ActionRunContext } from \"../agent/production-agent.js\";\nimport { findAgent, discoverAgents } from \"../server/agent-discovery.js\";\nimport {\n A2AClient,\n A2ATaskTimeoutError,\n callAgent,\n signA2AToken,\n} from \"../a2a/client.js\";\nimport { A2A_CONTINUATION_QUEUED_MARKER } from \"../integrations/a2a-continuation-marker.js\";\nimport {\n getRequestUserEmail,\n getRequestOrgId,\n isIntegrationCallerRequest,\n getIntegrationRequestContext,\n} from \"../server/request-context.js\";\nimport { getOrgDomain, getOrgA2ASecret } from \"../org/context.js\";\n\nconst DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS = 18_000;\nconst NETLIFY_INTEGRATION_A2A_TIMEOUT_MS = 50_000;\nconst INTEGRATION_A2A_TOKEN_TTL = \"30m\";\n\nfunction parseTimeoutMs(value: string | undefined): number | undefined {\n if (!value) return undefined;\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed <= 0) return undefined;\n return Math.floor(parsed);\n}\n\nfunction isServerlessHost(): boolean {\n // Detection mirrors db/migrations.ts:297-301. On Cloudflare Workers/Pages,\n // `process.env` is shimmed and CF_PAGES isn't reliably populated at runtime —\n // the canonical signal is the `__cf_env` global injected by workerd.\n return (\n !!process.env.NETLIFY ||\n !!process.env.AWS_LAMBDA_FUNCTION_NAME ||\n !!process.env.VERCEL ||\n \"__cf_env\" in globalThis\n );\n}\n\nfunction getIntegrationCallTimeoutMs(): number | undefined {\n if (!isServerlessHost() || !isIntegrationCallerRequest()) return undefined;\n\n const configured = parseTimeoutMs(\n process.env.AGENT_NATIVE_INTEGRATION_A2A_TIMEOUT_MS,\n );\n if (configured !== undefined) return configured;\n\n // Netlify's current synchronous function budget is 60s, but leave room for\n // cold start, polling overhead, and the caller's final platform response.\n if (process.env.NETLIFY) return NETLIFY_INTEGRATION_A2A_TIMEOUT_MS;\n\n return DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS;\n}\n\nexport const tool: ActionTool = {\n description:\n \"Call a DIFFERENT, separately-deployed agent app to ask a question or delegate a task. This is strictly for cross-app A2A communication — for example, asking the mail agent to send an email while you are the calendar agent. NEVER use this to call your own app or perform actions you can do with your own tools. Using call-agent on yourself will fail and waste time. \" +\n \"IMPORTANT — handling the response: \" +\n \"(a) If it contains a URL or ID, copy it VERBATIM into your reply. Do not 'correct' or pluralize the path (e.g. /deck/ → /decks/), normalize casing, or change the slug — any edit breaks the link. \" +\n '(b) If it does NOT contain a URL/ID and the user asked for one, say so explicitly (e.g. \"the agent created the deck but didn\\'t return a link — open the app directly to view it\"). NEVER invent a URL, slug, or path — guessing produces broken links that look real.',\n parameters: {\n type: \"object\",\n properties: {\n agent: {\n type: \"string\",\n description:\n \"Name or URL of a DIFFERENT deployed agent app (e.g. 'mail', 'calendar', 'analytics'). Must not be the current app's own name.\",\n },\n message: {\n type: \"string\",\n description: \"The message/question to send to the other agent\",\n },\n },\n required: [\"agent\", \"message\"],\n },\n};\n\nexport async function run(\n args: Record<string, string>,\n context?: ActionRunContext,\n selfAppId?: string,\n): Promise<string> {\n const { agent: agentIdOrName, message } = args;\n\n if (!agentIdOrName) return \"Error: --agent is required\";\n if (!message) return \"Error: --message is required\";\n\n // Prevent self-calls — the agent must use its own registered tools instead\n if (selfAppId && agentIdOrName.toLowerCase() === selfAppId.toLowerCase()) {\n return `Error: You cannot use call-agent to call yourself (${selfAppId}). Use your own registered actions/tools instead. call-agent is only for communicating with OTHER separately-deployed apps.`;\n }\n\n const agent = await findAgent(agentIdOrName, selfAppId);\n if (!agent) {\n const available = (await discoverAgents(selfAppId))\n .map((a) => a.name)\n .join(\", \");\n return `Error: Agent \"${agentIdOrName}\" not found. Available agents: ${available || \"(none)\"}`;\n }\n\n // Append a small cross-app hint to the outgoing message so the receiving\n // agent (which may be on an older deploy without the receiver-side hint\n // in handlers.ts) still emits fully-qualified URLs. This is belt-and-\n // suspenders with the receiver hint — but it works against any current\n // deployment, no redeploy required.\n const messageWithHint =\n `${message}\\n\\n` +\n `[Note: this request comes from another app via A2A. The caller cannot see your local UI, deck list, or navigation — only the literal text you put in your reply. ` +\n `If you create or reference a deck/document/dashboard, include its FULLY-QUALIFIED URL (e.g. ${agent.url}/deck/<id>) in your reply, not a relative path. ` +\n `Use only IDs returned by your own actions — never invent slugs or hosts.]`;\n\n try {\n // If we have a send context, use streaming so the UI shows progressive text\n if (context?.send) {\n const callerEmail = getRequestUserEmail();\n\n // Build metadata with identity\n const a2aMetadata: Record<string, unknown> = {};\n if (callerEmail) a2aMetadata.userEmail = callerEmail;\n\n // Include org domain for cross-app org resolution\n let callerOrgDomain: string | undefined;\n let callerOrgSecret: string | undefined;\n const orgId = getRequestOrgId();\n if (orgId) {\n try {\n const domain = await getOrgDomain(orgId);\n if (domain) {\n callerOrgDomain = domain;\n a2aMetadata.orgDomain = domain;\n }\n } catch {}\n try {\n const secret = await getOrgA2ASecret(orgId);\n if (secret) callerOrgSecret = secret;\n } catch {}\n }\n\n // Sign JWT with identity + org domain for the streaming client\n let apiKey: string | undefined;\n if (callerEmail && (callerOrgSecret || process.env.A2A_SECRET)) {\n try {\n apiKey = await signA2AToken(\n callerEmail,\n callerOrgDomain,\n callerOrgSecret,\n { expiresIn: INTEGRATION_A2A_TOKEN_TTL },\n );\n } catch {}\n }\n\n const client = new A2AClient(agent.url, apiKey);\n\n if (process.env.NODE_ENV === \"production\" && callerEmail) {\n try {\n const { listOAuthAccountsByOwner } =\n await import(\"../oauth-tokens/store.js\");\n const accounts = await listOAuthAccountsByOwner(\n \"google\",\n callerEmail,\n );\n const tokens = accounts[0]?.tokens;\n if (tokens?.access_token) {\n a2aMetadata.googleToken = tokens.access_token;\n }\n } catch {}\n }\n\n let responseText = \"\";\n let lastSentLength = 0;\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"start\",\n });\n\n const emitNewText = (newText: string) => {\n if (newText.length > lastSentLength) {\n context.send!({\n type: \"agent_call_text\",\n agent: agent.name,\n text: newText.slice(lastSentLength),\n });\n lastSentLength = newText.length;\n }\n responseText = newText;\n };\n\n // Skip the SSE streaming attempt and go straight to async + poll.\n // Why: on Netlify (Lambda), the receiving server has no streaming\n // response support, so message/stream returns a single JSON-RPC error\n // body in a 200 response that our SSE parser silently consumes — the\n // `for await` loop yields nothing AND keeps the connection open until\n // the function timeout, eating the current serverless budget. By the\n // time we get to the sync fallback, Lambda is dead and the second fetch\n // errors out as \"fetch failed\". Async+poll has its own short fetches\n // with their own budgets, so it works reliably across hosts. The\n // trade-off is we lose progressive in-UI text streaming for cross-app\n // A2A calls, but the receiving agent's full response still surfaces via\n // the tool_result event below.\n try {\n // Apply a polling cap ONLY for integration-platform callers on\n // serverless hosts. Normal chat, local Node, self-hosted Node, and\n // Docker can wait for slow-but-valid answers; integration processors\n // still need to finish before their current function execution dies.\n const callTimeoutMs = getIntegrationCallTimeoutMs();\n responseText = await callAgent(agent.url, messageWithHint, {\n apiKey,\n userEmail: callerEmail,\n orgDomain: callerOrgDomain,\n orgSecret: callerOrgSecret,\n ...(callTimeoutMs ? { timeoutMs: callTimeoutMs } : {}),\n });\n // Some agents reply with relative paths (e.g. slides emits\n // \"/deck/abc\"). Those resolve against the caller's host, not the\n // receiver's, so they're broken for the user. Expand any leading-slash\n // URL into a fully-qualified one rooted at the receiving agent's host.\n responseText = expandRelativeUrls(responseText, agent.url);\n // Mirror the response into the streaming UI so the user sees it.\n if (responseText) emitNewText(responseText);\n } catch (pollErr: any) {\n if (pollErr instanceof A2ATaskTimeoutError) {\n const queued = await enqueueIntegrationContinuationIfPossible(\n pollErr,\n agent,\n callerEmail,\n apiKey,\n );\n if (queued) {\n responseText = `${A2A_CONTINUATION_QUEUED_MARKER}\\nThe ${agent.name} agent is still working. Do not send an interim reply to the user; the final result will be posted to the originating integration thread automatically.`;\n } else {\n const reason = pollErr?.message ?? \"unknown error\";\n responseText = `The ${agent.name} agent is taking longer than expected and didn't reply in time. (${reason})`;\n }\n } else {\n const reason = pollErr?.message ?? \"unknown error\";\n responseText = `The ${agent.name} agent is taking longer than expected and didn't reply in time. (${reason})`;\n }\n }\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"done\",\n });\n\n return responseText || \"(empty response)\";\n }\n\n // No context — use the async + poll call so we don't get cut off at the\n // serverless gateway's ~30s timeout. callAgent defaults to async:true.\n const email = getRequestUserEmail();\n let domain: string | undefined;\n let orgSecret: string | undefined;\n const currentOrgId = getRequestOrgId();\n if (currentOrgId) {\n try {\n domain = (await getOrgDomain(currentOrgId)) ?? undefined;\n } catch {}\n try {\n orgSecret = (await getOrgA2ASecret(currentOrgId)) ?? undefined;\n } catch {}\n }\n const response = await callAgent(agent.url, messageWithHint, {\n userEmail: email,\n orgDomain: domain,\n orgSecret,\n });\n return expandRelativeUrls(response, agent.url) || \"(empty response)\";\n } catch (err: any) {\n const msg = err?.message ?? String(err);\n // Friendlier message for the common timeout case so the calling agent can\n // decide whether to give up or retry.\n if (/timeout|did not complete|Inactivity|504/i.test(msg)) {\n return `The ${agent.name} agent is taking longer than expected. Please try again, ask a simpler question, or open the ${agent.name} app directly.`;\n }\n return `Error calling ${agent.name}: ${msg}`;\n }\n}\n\nasync function enqueueIntegrationContinuationIfPossible(\n error: A2ATaskTimeoutError,\n agent: { name: string; url: string },\n ownerEmail: string | undefined,\n a2aAuthToken: string | undefined,\n): Promise<boolean> {\n const integration = getIntegrationRequestContext();\n if (!integration || !ownerEmail) return false;\n\n try {\n const [{ insertA2AContinuation }, { dispatchA2AContinuation }] =\n await Promise.all([\n import(\"../integrations/a2a-continuations-store.js\"),\n import(\"../integrations/a2a-continuation-processor.js\"),\n ]);\n const continuation = await insertA2AContinuation({\n integrationTaskId: integration.taskId,\n platform: integration.incoming.platform,\n externalThreadId: integration.incoming.externalThreadId,\n incoming: integration.incoming,\n placeholderRef: integration.placeholderRef,\n ownerEmail,\n orgId: getRequestOrgId() ?? null,\n agentName: agent.name,\n agentUrl: agent.url,\n a2aTaskId: error.taskId,\n a2aAuthToken: a2aAuthToken ?? \"\",\n });\n await dispatchA2AContinuation(continuation.id).catch((err) => {\n console.error(\n `[call-agent] Failed to dispatch A2A continuation ${continuation.id}:`,\n err,\n );\n });\n return true;\n } catch (err) {\n console.error(\"[call-agent] Failed to enqueue A2A continuation:\", err);\n return false;\n }\n}\n\n// Expand bare leading-slash paths (e.g. \"/deck/abc\") into fully-qualified URLs\n// rooted at the receiving agent's host. The receiver doesn't always know it's\n// being called cross-app, so it may emit relative paths that resolve against\n// the caller's host (broken). Match a path that starts at a word boundary,\n// begins with `/`, and has at least one path segment after that. Skip if it\n// already looks like a fully-qualified URL.\nexport function expandRelativeUrls(text: string, agentUrl: string): string {\n if (!text || !agentUrl) return text;\n const base = agentUrl.replace(/\\/$/, \"\");\n // Path must start at boundary (start, whitespace, or punctuation that isn't\n // ':' — to avoid mangling `https://example.com/foo` or markdown link bodies).\n return text.replace(\n /(^|[\\s(\\[<\"'`])(\\/[a-z0-9_-][a-z0-9_/?&=%#.,:-]*)/gi,\n (_match, lead, path) => `${lead}${base}${path}`,\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"call-agent.js","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACzE,OAAO,EACL,SAAS,EACT,mBAAmB,EACnB,SAAS,EACT,YAAY,GACb,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,8BAA8B,EAAE,MAAM,4CAA4C,CAAC;AAC5F,OAAO,EACL,mBAAmB,EACnB,eAAe,EACf,0BAA0B,EAC1B,4BAA4B,GAC7B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAElE,MAAM,6CAA6C,GAAG,MAAM,CAAC;AAC7D,MAAM,kCAAkC,GAAG,MAAM,CAAC;AAClD,MAAM,yBAAyB,GAAG,KAAK,CAAC;AAExC,SAAS,cAAc,CAAC,KAAyB;IAC/C,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;IAC7B,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,MAAM,IAAI,CAAC;QAAE,OAAO,SAAS,CAAC;IAC9D,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;AAC5B,CAAC;AAED,SAA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,CAAC,OAAO,CACjB,qDAAqD,EACrD,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,EAAE,CAChD,CAAC;AACJ,CAAC","sourcesContent":["import type { ActionTool } from \"../agent/types.js\";\nimport type { ActionRunContext } from \"../agent/production-agent.js\";\nimport { findAgent, discoverAgents } from \"../server/agent-discovery.js\";\nimport {\n A2AClient,\n A2ATaskTimeoutError,\n callAgent,\n signA2AToken,\n} from \"../a2a/client.js\";\nimport { A2A_CONTINUATION_QUEUED_MARKER } from \"../integrations/a2a-continuation-marker.js\";\nimport {\n getRequestUserEmail,\n getRequestOrgId,\n isIntegrationCallerRequest,\n getIntegrationRequestContext,\n} from \"../server/request-context.js\";\nimport { getOrgDomain, getOrgA2ASecret } from \"../org/context.js\";\n\nconst DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS = 18_000;\nconst NETLIFY_INTEGRATION_A2A_TIMEOUT_MS = 50_000;\nconst INTEGRATION_A2A_TOKEN_TTL = \"30m\";\n\nfunction parseTimeoutMs(value: string | undefined): number | undefined {\n if (!value) return undefined;\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed <= 0) return undefined;\n return Math.floor(parsed);\n}\n\nfunction isServerlessHost(): boolean {\n // Detection mirrors db/migrations.ts:297-301. On Cloudflare Workers/Pages,\n // `process.env` is shimmed and CF_PAGES isn't reliably populated at runtime —\n // the canonical signal is the `__cf_env` global injected by workerd.\n return (\n !!process.env.NETLIFY ||\n !!process.env.AWS_LAMBDA_FUNCTION_NAME ||\n !!process.env.VERCEL ||\n \"__cf_env\" in globalThis\n );\n}\n\nfunction getIntegrationCallTimeoutMs(): number | undefined {\n if (!isServerlessHost() || !isIntegrationCallerRequest()) return undefined;\n\n const configured = parseTimeoutMs(\n process.env.AGENT_NATIVE_INTEGRATION_A2A_TIMEOUT_MS,\n );\n if (configured !== undefined) return configured;\n\n // Netlify's current synchronous function budget is 60s, but leave room for\n // cold start, polling overhead, and the caller's final platform response.\n if (process.env.NETLIFY) return NETLIFY_INTEGRATION_A2A_TIMEOUT_MS;\n\n return DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS;\n}\n\nexport const tool: ActionTool = {\n description:\n \"Call a DIFFERENT, separately-deployed agent app to ask a question or delegate a task. This is strictly for cross-app A2A communication — for example, asking the mail agent to send an email while you are the calendar agent. NEVER use this to call your own app or perform actions you can do with your own tools. Using call-agent on yourself will fail and waste time. \" +\n \"IMPORTANT — handling the response: \" +\n \"(a) If it contains a URL or ID, copy it VERBATIM into your reply. Do not 'correct' or pluralize the path (e.g. /deck/ → /decks/), normalize casing, or change the slug — any edit breaks the link. \" +\n '(b) If it does NOT contain a URL/ID and the user asked for one, say so explicitly (e.g. \"the agent created the deck but didn\\'t return a link — open the app directly to view it\"). NEVER invent a URL, slug, or path — guessing produces broken links that look real.',\n parameters: {\n type: \"object\",\n properties: {\n agent: {\n type: \"string\",\n description:\n \"Name or URL of a DIFFERENT deployed agent app (e.g. 'mail', 'calendar', 'analytics'). Must not be the current app's own name.\",\n },\n message: {\n type: \"string\",\n description: \"The message/question to send to the other agent\",\n },\n },\n required: [\"agent\", \"message\"],\n },\n};\n\nexport async function run(\n args: Record<string, string>,\n context?: ActionRunContext,\n selfAppId?: string,\n): Promise<string> {\n const { agent: agentIdOrName, message } = args;\n\n if (!agentIdOrName) return \"Error: --agent is required\";\n if (!message) return \"Error: --message is required\";\n\n // Prevent self-calls — the agent must use its own registered tools instead\n if (selfAppId && agentIdOrName.toLowerCase() === selfAppId.toLowerCase()) {\n return `Error: You cannot use call-agent to call yourself (${selfAppId}). Use your own registered actions/tools instead. call-agent is only for communicating with OTHER separately-deployed apps.`;\n }\n\n const agent = await findAgent(agentIdOrName, selfAppId);\n if (!agent) {\n const available = (await discoverAgents(selfAppId))\n .map((a) => a.name)\n .join(\", \");\n return `Error: Agent \"${agentIdOrName}\" not found. Available agents: ${available || \"(none)\"}`;\n }\n\n // Append a small cross-app hint to the outgoing message so the receiving\n // agent (which may be on an older deploy without the receiver-side hint\n // in handlers.ts) still emits fully-qualified URLs. This is belt-and-\n // suspenders with the receiver hint — but it works against any current\n // deployment, no redeploy required.\n const messageWithHint =\n `${message}\\n\\n` +\n `[Note: this request comes from another app via A2A. The caller cannot see your local UI, deck list, or navigation — only the literal text you put in your reply. ` +\n `If you create or reference a deck/document/dashboard, include its FULLY-QUALIFIED URL (e.g. ${agent.url}/deck/<id>) in your reply, not a relative path. ` +\n `Use only IDs returned by your own actions — never invent slugs or hosts.]`;\n\n try {\n // If we have a send context, use streaming so the UI shows progressive text\n if (context?.send) {\n const callerEmail = getRequestUserEmail();\n\n // Build metadata with identity\n const a2aMetadata: Record<string, unknown> = {};\n if (callerEmail) a2aMetadata.userEmail = callerEmail;\n\n // Include org domain for cross-app org resolution\n let callerOrgDomain: string | undefined;\n let callerOrgSecret: string | undefined;\n const orgId = getRequestOrgId();\n if (orgId) {\n try {\n const domain = await getOrgDomain(orgId);\n if (domain) {\n callerOrgDomain = domain;\n a2aMetadata.orgDomain = domain;\n }\n } catch {}\n try {\n const secret = await getOrgA2ASecret(orgId);\n if (secret) callerOrgSecret = secret;\n } catch {}\n }\n\n // Sign JWT with identity + org domain for the streaming client\n let apiKey: string | undefined;\n if (callerEmail && (callerOrgSecret || process.env.A2A_SECRET)) {\n try {\n apiKey = await signA2AToken(\n callerEmail,\n callerOrgDomain,\n callerOrgSecret,\n {\n expiresIn: INTEGRATION_A2A_TOKEN_TTL,\n preferGlobalSecret: true,\n },\n );\n } catch {}\n }\n\n const client = new A2AClient(agent.url, apiKey);\n\n if (process.env.NODE_ENV === \"production\" && callerEmail) {\n try {\n const { listOAuthAccountsByOwner } =\n await import(\"../oauth-tokens/store.js\");\n const accounts = await listOAuthAccountsByOwner(\n \"google\",\n callerEmail,\n );\n const tokens = accounts[0]?.tokens;\n if (tokens?.access_token) {\n a2aMetadata.googleToken = tokens.access_token;\n }\n } catch {}\n }\n\n let responseText = \"\";\n let lastSentLength = 0;\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"start\",\n });\n\n const emitNewText = (newText: string) => {\n if (newText.length > lastSentLength) {\n context.send!({\n type: \"agent_call_text\",\n agent: agent.name,\n text: newText.slice(lastSentLength),\n });\n lastSentLength = newText.length;\n }\n responseText = newText;\n };\n\n // Skip the SSE streaming attempt and go straight to async + poll.\n // Why: on Netlify (Lambda), the receiving server has no streaming\n // response support, so message/stream returns a single JSON-RPC error\n // body in a 200 response that our SSE parser silently consumes — the\n // `for await` loop yields nothing AND keeps the connection open until\n // the function timeout, eating the current serverless budget. By the\n // time we get to the sync fallback, Lambda is dead and the second fetch\n // errors out as \"fetch failed\". Async+poll has its own short fetches\n // with their own budgets, so it works reliably across hosts. The\n // trade-off is we lose progressive in-UI text streaming for cross-app\n // A2A calls, but the receiving agent's full response still surfaces via\n // the tool_result event below.\n try {\n // Apply a polling cap ONLY for integration-platform callers on\n // serverless hosts. Normal chat, local Node, self-hosted Node, and\n // Docker can wait for slow-but-valid answers; integration processors\n // still need to finish before their current function execution dies.\n const callTimeoutMs = getIntegrationCallTimeoutMs();\n responseText = await callAgent(agent.url, messageWithHint, {\n apiKey,\n userEmail: callerEmail,\n orgDomain: callerOrgDomain,\n orgSecret: callerOrgSecret,\n ...(callTimeoutMs ? { timeoutMs: callTimeoutMs } : {}),\n });\n // Some agents reply with relative paths (e.g. slides emits\n // \"/deck/abc\"). Those resolve against the caller's host, not the\n // receiver's, so they're broken for the user. Expand any leading-slash\n // URL into a fully-qualified one rooted at the receiving agent's host.\n responseText = expandRelativeUrls(responseText, agent.url);\n // Mirror the response into the streaming UI so the user sees it.\n if (responseText) emitNewText(responseText);\n } catch (pollErr: any) {\n if (pollErr instanceof A2ATaskTimeoutError) {\n const queued = await enqueueIntegrationContinuationIfPossible(\n pollErr,\n agent,\n callerEmail,\n );\n if (queued) {\n responseText = `${A2A_CONTINUATION_QUEUED_MARKER}\\nThe ${agent.name} agent is still working. Do not send an interim reply to the user; the final result will be posted to the originating integration thread automatically.`;\n } else {\n const reason = pollErr?.message ?? \"unknown error\";\n responseText = `The ${agent.name} agent is taking longer than expected and didn't reply in time. (${reason})`;\n }\n } else {\n const reason = pollErr?.message ?? \"unknown error\";\n responseText = `The ${agent.name} agent is taking longer than expected and didn't reply in time. (${reason})`;\n }\n }\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"done\",\n });\n\n return responseText || \"(empty response)\";\n }\n\n // No context — use the async + poll call so we don't get cut off at the\n // serverless gateway's ~30s timeout. callAgent defaults to async:true.\n const email = getRequestUserEmail();\n let domain: string | undefined;\n let orgSecret: string | undefined;\n const currentOrgId = getRequestOrgId();\n if (currentOrgId) {\n try {\n domain = (await getOrgDomain(currentOrgId)) ?? undefined;\n } catch {}\n try {\n orgSecret = (await getOrgA2ASecret(currentOrgId)) ?? undefined;\n } catch {}\n }\n const response = await callAgent(agent.url, messageWithHint, {\n userEmail: email,\n orgDomain: domain,\n orgSecret,\n });\n return expandRelativeUrls(response, agent.url) || \"(empty response)\";\n } catch (err: any) {\n const msg = err?.message ?? String(err);\n // Friendlier message for the common timeout case so the calling agent can\n // decide whether to give up or retry.\n if (/timeout|did not complete|Inactivity|504/i.test(msg)) {\n return `The ${agent.name} agent is taking longer than expected. Please try again, ask a simpler question, or open the ${agent.name} app directly.`;\n }\n return `Error calling ${agent.name}: ${msg}`;\n }\n}\n\nasync function enqueueIntegrationContinuationIfPossible(\n error: A2ATaskTimeoutError,\n agent: { name: string; url: string },\n ownerEmail: string | undefined,\n): Promise<boolean> {\n const integration = getIntegrationRequestContext();\n if (!integration || !ownerEmail) return false;\n\n try {\n const [{ insertA2AContinuation }, { dispatchA2AContinuation }] =\n await Promise.all([\n import(\"../integrations/a2a-continuations-store.js\"),\n import(\"../integrations/a2a-continuation-processor.js\"),\n ]);\n const continuation = await insertA2AContinuation({\n integrationTaskId: integration.taskId,\n platform: integration.incoming.platform,\n externalThreadId: integration.incoming.externalThreadId,\n incoming: integration.incoming,\n placeholderRef: integration.placeholderRef,\n ownerEmail,\n orgId: getRequestOrgId() ?? null,\n agentName: agent.name,\n agentUrl: agent.url,\n a2aTaskId: error.taskId,\n // Do not persist the short-lived JWT used for the initial send. The\n // continuation processor can mint a fresh token for each poll.\n a2aAuthToken: null,\n });\n await dispatchA2AContinuation(continuation.id).catch((err) => {\n console.error(\n `[call-agent] Failed to dispatch A2A continuation ${continuation.id}:`,\n err,\n );\n });\n return true;\n } catch (err) {\n console.error(\"[call-agent] Failed to enqueue A2A continuation:\", err);\n return false;\n }\n}\n\n// Expand bare leading-slash paths (e.g. \"/deck/abc\") into fully-qualified URLs\n// rooted at the receiving agent's host. The receiver doesn't always know it's\n// being called cross-app, so it may emit relative paths that resolve against\n// the caller's host (broken). Match a path that starts at a word boundary,\n// begins with `/`, and has at least one path segment after that. Skip if it\n// already looks like a fully-qualified URL.\nexport function expandRelativeUrls(text: string, agentUrl: string): string {\n if (!text || !agentUrl) return text;\n const base = agentUrl.replace(/\\/$/, \"\");\n // Path must start at boundary (start, whitespace, or punctuation that isn't\n // ':' — to avoid mangling `https://example.com/foo` or markdown link bodies).\n return text.replace(\n /(^|[\\s(\\[<\"'`])(\\/[a-z0-9_-][a-z0-9_/?&=%#.,:-]*)/gi,\n (_match, lead, path) => `${lead}${base}${path}`,\n );\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-discovery.d.ts","sourceRoot":"","sources":["../../src/server/agent-discovery.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,eAAe;IAC9B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;CACf;AA+CD;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,eAAe,EAAE,CAUtE;AAED;;;GAGG;AACH,wBAAsB,cAAc,CAClC,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,eAAe,EAAE,CAAC,
|
|
1
|
+
{"version":3,"file":"agent-discovery.d.ts","sourceRoot":"","sources":["../../src/server/agent-discovery.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,eAAe;IAC9B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;CACf;AA+CD;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,eAAe,EAAE,CAUtE;AAED;;;GAGG;AACH,wBAAsB,cAAc,CAClC,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,eAAe,EAAE,CAAC,CA8E5B;AAED;;GAEG;AACH,wBAAsB,SAAS,CAC7B,QAAQ,EAAE,MAAM,EAChB,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC,CAItC;AAsND;;;;;;GAMG;AACH,eAAO,MAAM,0BAA0B,EAAE,eAAe,EAOnD,CAAC"}
|
|
@@ -49,10 +49,13 @@ export async function discoverAgents(selfAppId) {
|
|
|
49
49
|
const { resourceList, resourceGet, SHARED_OWNER, resourceListAccessible } = await import("../resources/store.js");
|
|
50
50
|
const { DEV_MODE_USER_EMAIL } = await import("./auth.js");
|
|
51
51
|
const isDevMode = typeof process !== "undefined" && process.env?.NODE_ENV !== "production";
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
52
|
+
const { parseRemoteAgentManifest, REMOTE_AGENT_RESOURCE_PREFIXES } = await import("../resources/metadata.js");
|
|
53
|
+
const resources = [];
|
|
54
|
+
for (const prefix of [...REMOTE_AGENT_RESOURCE_PREFIXES].reverse()) {
|
|
55
|
+
resources.push(...(isDevMode
|
|
56
|
+
? await resourceListAccessible(DEV_MODE_USER_EMAIL, prefix)
|
|
57
|
+
: await resourceList(SHARED_OWNER, prefix)));
|
|
58
|
+
}
|
|
56
59
|
for (const r of resources) {
|
|
57
60
|
if (!r.path.endsWith(".json"))
|
|
58
61
|
continue;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-discovery.js","sourceRoot":"","sources":["../../src/server/agent-discovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAoBvE;;;;GAIG;AACH,MAAM,cAAc,GAAiB,gBAAgB,EAAE;KACpD,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC;KACxC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IAClB,EAAE,EAAE,QAAQ,CAAC,IAAI;IACjB,IAAI,EAAE,QAAQ,CAAC,KAAK;IACpB,WAAW,EAAE,QAAQ,CAAC,WAAW,IAAI,QAAQ,CAAC,IAAI;IAClD,GAAG,EAAE,QAAQ,CAAC,OAAQ;IACtB,MAAM,EAAE,oBAAoB,QAAQ,CAAC,OAAO,EAAE;IAC9C,OAAO,EAAE,QAAQ,CAAC,OAAO;IACzB,KAAK,EAAE,QAAQ,CAAC,KAAK;CACtB,CAAC,CAAC,CAAC;AAEN,MAAM,4BAA4B,GAAG,IAAI,GAAG,CAC1C,SAAS,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,MAAM,IAAI,QAAQ,CAAC,OAAO,CAAC,CAAC,GAAG,CACrE,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,CAC5B,CACF,CAA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KAAK,EAAE,OAAO,EAAE,KAAK,IAAI,SAAS;SACT,CAAC;IAC9B,CAAC,CAAC;SACD,MAAM,CAAC,CAAC,KAAK,EAA4B,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;AAC1D,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,0BAA0B,GACrC,cAAc,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IACpD,EAAE,EAAE,GAAG,CAAC,EAAE;IACV,IAAI,EAAE,GAAG,CAAC,IAAI;IACd,WAAW,EAAE,GAAG,CAAC,WAAW;IAC5B,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,cAAc;IAC5B,KAAK,EAAE,GAAG,CAAC,KAAK;CACjB,CAAC,CAAC,CAAC","sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { TEMPLATES, visibleTemplates } from \"../cli/templates-meta.js\";\n\nexport interface DiscoveredAgent {\n id: string;\n name: string;\n description: string;\n url: string;\n color: string;\n}\n\ninterface AgentEntry {\n id: string;\n name: string;\n description: string;\n url: string;\n devUrl?: string;\n devPort: number;\n color: string;\n}\n\n/**\n * Built-in agent registry. Derive this from the published CLI metadata so\n * connected-agent discovery stays aligned with the public template allow-list\n * without depending on @agent-native/shared-app-config at runtime.\n */\nconst BUILTIN_AGENTS: AgentEntry[] = visibleTemplates()\n .filter((template) => !!template.prodUrl)\n .map((template) => ({\n id: template.name,\n name: template.label,\n description: template.description ?? template.hint,\n url: template.prodUrl!,\n devUrl: `http://localhost:${template.devPort}`,\n devPort: template.devPort,\n color: template.color,\n }));\n\nconst HIDDEN_FIRST_PARTY_AGENT_IDS = new Set(\n TEMPLATES.filter((template) => template.hidden && template.prodUrl).map(\n (template) => template.name,\n ),\n);\n\nconst WORKSPACE_APPS_ENV_KEY = \"AGENT_NATIVE_WORKSPACE_APPS_JSON\";\nconst WORKSPACE_APPS_MANIFEST_FILE = \"workspace-apps.json\";\n\ninterface WorkspaceAppManifestEntry {\n id: string;\n name: string;\n description: string;\n path: string;\n url?: string | null;\n isDispatch?: boolean;\n}\n\n/**\n * Get built-in agents (static, no DB). Used as fallback and for seeding.\n */\nexport function getBuiltinAgents(selfAppId?: string): DiscoveredAgent[] {\n return BUILTIN_AGENTS.filter((app) => app.id !== selfAppId && app.url).map(\n (app) => ({\n id: app.id,\n name: app.name,\n description: app.description,\n url: resolveAgentUrl(app),\n color: app.color,\n }),\n );\n}\n\n/**\n * Discover all agents: built-in + custom agents stored as resources.\n * Custom agents override built-in agents with the same ID.\n */\nexport async function discoverAgents(\n selfAppId?: string,\n): Promise<DiscoveredAgent[]> {\n const builtins = getBuiltinAgents(selfAppId);\n const agentsById = new Map<string, DiscoveredAgent>();\n\n // Start with built-ins\n for (const agent of builtins) {\n agentsById.set(agent.id, agent);\n }\n\n // Overlay custom agents from resources\n try {\n const { resourceList, resourceGet, SHARED_OWNER, resourceListAccessible } =\n await import(\"../resources/store.js\");\n const { DEV_MODE_USER_EMAIL } = await import(\"./auth.js\");\n\n const isDevMode =\n typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\";\n\n const resources = isDevMode\n ? await resourceListAccessible(DEV_MODE_USER_EMAIL, \"remote-agents/\")\n : await resourceList(SHARED_OWNER, \"remote-agents/\");\n const { parseRemoteAgentManifest } =\n await import(\"../resources/metadata.js\");\n\n for (const r of resources) {\n if (!r.path.endsWith(\".json\")) continue;\n try {\n const full = await resourceGet(r.id);\n if (!full) continue;\n const manifest = parseRemoteAgentManifest(full.content, r.path);\n if (!manifest || manifest.id === selfAppId) continue;\n if (HIDDEN_FIRST_PARTY_AGENT_IDS.has(manifest.id)) continue;\n\n // If the resource override carries a localhost URL but we're running\n // in production (e.g. a stale dev-time seed got promoted to the prod\n // DB), fall back to the matching built-in's prod URL instead of\n // letting the override win — otherwise outbound `call-agent` fetches\n // from a serverless function would target localhost and fail with\n // \"fetch failed\" instantly. The override still wins for non-localhost\n // URLs (the supported case for self-hosted custom agents).\n let url = manifest.url;\n if (\n !isDevMode &&\n typeof url === \"string\" &&\n /^https?:\\/\\/(localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0)(:|\\/|$)/.test(url)\n ) {\n const builtin = agentsById.get(manifest.id);\n if (builtin?.url) url = builtin.url;\n }\n\n agentsById.set(manifest.id, {\n id: manifest.id,\n name: manifest.name,\n description: manifest.description || \"\",\n url,\n color: manifest.color || \"#6B7280\",\n });\n } catch {\n // Skip unreadable resources\n }\n }\n } catch {\n // Resources not available — use built-ins only\n }\n\n // Overlay sibling workspace apps last so same-origin workspaces prefer the\n // app mounted in this workspace over the public template with the same id.\n for (const agent of discoverWorkspaceAgents(selfAppId)) {\n agentsById.set(agent.id, agent);\n }\n\n return Array.from(agentsById.values());\n}\n\n/**\n * Look up a single agent by ID or name (case-insensitive).\n */\nexport async function findAgent(\n idOrName: string,\n selfAppId?: string,\n): Promise<DiscoveredAgent | undefined> {\n const lower = idOrName.toLowerCase();\n const agents = await discoverAgents(selfAppId);\n return agents.find((a) => a.id === lower || a.name.toLowerCase() === lower);\n}\n\nfunction isDevEnvironment(): boolean {\n return (\n typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\"\n );\n}\n\nfunction resolveAgentUrl(app: AgentEntry): string {\n if (isDevEnvironment()) {\n return app.devUrl || `http://localhost:${app.devPort}`;\n }\n return app.url;\n}\n\nfunction readJson(file: string): any {\n try {\n return JSON.parse(fs.readFileSync(file, \"utf8\"));\n } catch {\n return null;\n }\n}\n\nfunction findWorkspaceRoot(startDir = process.cwd()): string | null {\n let dir = path.resolve(startDir);\n for (let i = 0; i < 20; i++) {\n const pkg = readJson(path.join(dir, \"package.json\"));\n if (typeof pkg?.[\"agent-native\"]?.workspaceCore === \"string\") {\n return dir;\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\nfunction titleCase(value: string): string {\n return value\n .split(/[-_\\s]+/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(\" \");\n}\n\nfunction parseWorkspaceAppsManifest(\n parsed: any,\n): WorkspaceAppManifestEntry[] | null {\n const rawApps = Array.isArray(parsed?.apps)\n ? parsed.apps\n : Array.isArray(parsed)\n ? parsed\n : null;\n if (!rawApps) return null;\n\n const apps = rawApps\n .map((entry) => {\n if (!entry || typeof entry !== \"object\") return null;\n const id = typeof entry.id === \"string\" ? entry.id.trim() : \"\";\n const pathValue = typeof entry.path === \"string\" ? entry.path.trim() : \"\";\n if (!id || !pathValue.startsWith(\"/\")) return null;\n return {\n id,\n name:\n typeof entry.name === \"string\" && entry.name.trim()\n ? entry.name.trim()\n : titleCase(id),\n description:\n typeof entry.description === \"string\" ? entry.description : \"\",\n path: pathValue,\n url:\n typeof entry.url === \"string\" && entry.url.trim()\n ? entry.url.trim()\n : null,\n isDispatch:\n typeof entry.isDispatch === \"boolean\"\n ? entry.isDispatch\n : id === \"dispatch\",\n } satisfies WorkspaceAppManifestEntry;\n })\n .filter((app): app is WorkspaceAppManifestEntry => !!app)\n .sort((a, b) => {\n if (a.id === \"dispatch\") return -1;\n if (b.id === \"dispatch\") return 1;\n return a.name.localeCompare(b.name);\n });\n\n return apps.length ? apps : null;\n}\n\nfunction readWorkspaceAppsFromEnv(): WorkspaceAppManifestEntry[] | null {\n const raw = process.env[WORKSPACE_APPS_ENV_KEY];\n if (!raw) return null;\n try {\n return parseWorkspaceAppsManifest(JSON.parse(raw));\n } catch {\n return null;\n }\n}\n\nfunction workspaceAppsManifestCandidates(): string[] {\n const candidates: string[] = [];\n try {\n candidates.push(\n path.join(process.cwd(), \".agent-native\", WORKSPACE_APPS_MANIFEST_FILE),\n path.join(process.cwd(), WORKSPACE_APPS_MANIFEST_FILE),\n );\n } catch {\n // Some edge runtimes do not expose process.cwd().\n }\n try {\n const moduleDir = path.dirname(fileURLToPath(import.meta.url));\n candidates.push(\n path.join(moduleDir, \".agent-native\", WORKSPACE_APPS_MANIFEST_FILE),\n path.join(moduleDir, WORKSPACE_APPS_MANIFEST_FILE),\n );\n } catch {\n // Some edge runtimes expose non-file module URLs. The env manifest still\n // works there, so skip file-relative candidates.\n }\n return candidates;\n}\n\nfunction readWorkspaceAppsFromManifestFile():\n | WorkspaceAppManifestEntry[]\n | null {\n for (const file of workspaceAppsManifestCandidates()) {\n if (!fs.existsSync(file)) continue;\n const apps = parseWorkspaceAppsManifest(readJson(file));\n if (apps) return apps;\n }\n return null;\n}\n\nfunction readWorkspaceAppsFromFilesystem(): WorkspaceAppManifestEntry[] | null {\n const workspaceRoot = findWorkspaceRoot();\n if (!workspaceRoot) return null;\n const appsDir = path.join(workspaceRoot, \"apps\");\n if (!fs.existsSync(appsDir)) return null;\n\n const apps = fs\n .readdirSync(appsDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry): WorkspaceAppManifestEntry | null => {\n const appDir = path.join(appsDir, entry.name);\n const pkg = readJson(path.join(appDir, \"package.json\"));\n if (!pkg) return null;\n return {\n id: entry.name,\n name: pkg.displayName || titleCase(entry.name),\n description: pkg.description || \"\",\n path: `/${entry.name}`,\n isDispatch: entry.name === \"dispatch\",\n } satisfies WorkspaceAppManifestEntry;\n })\n .filter((app): app is WorkspaceAppManifestEntry => !!app)\n .sort((a, b) => {\n if (a.id === \"dispatch\") return -1;\n if (b.id === \"dispatch\") return 1;\n return a.name.localeCompare(b.name);\n });\n\n return apps.length ? apps : null;\n}\n\nfunction workspaceBaseUrl(): string | null {\n return (\n process.env.WORKSPACE_GATEWAY_URL ||\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n process.env.BETTER_AUTH_URL ||\n null\n );\n}\n\nfunction workspaceAppUrl(app: WorkspaceAppManifestEntry): string | null {\n if (app.url) return app.url;\n const base = workspaceBaseUrl();\n if (!base) return null;\n try {\n return new URL(app.path, `${base.replace(/\\/$/, \"\")}/`).toString();\n } catch {\n return null;\n }\n}\n\nfunction discoverWorkspaceAgents(selfAppId?: string): DiscoveredAgent[] {\n const workspaceApps =\n readWorkspaceAppsFromEnv() ??\n readWorkspaceAppsFromManifestFile() ??\n readWorkspaceAppsFromFilesystem();\n if (!workspaceApps) return [];\n\n return workspaceApps\n .filter((app) => app.id !== selfAppId)\n .map((app) => {\n const url = workspaceAppUrl(app);\n if (!url) return null;\n const builtin = BUILTIN_AGENTS.find((agent) => agent.id === app.id);\n return {\n id: app.id,\n name: app.name,\n description:\n app.description ||\n builtin?.description ||\n `Workspace app mounted at ${app.path}`,\n url,\n color: builtin?.color || \"#6B7280\",\n } satisfies DiscoveredAgent;\n })\n .filter((agent): agent is DiscoveredAgent => !!agent);\n}\n\n/**\n * Like `getBuiltinAgents`, but always returns the production URL — never the\n * env-resolved devUrl. Used by the resource seeder so that a one-time seed\n * (`ON CONFLICT DO NOTHING`) can't permanently bake a localhost URL into the\n * DB, which would override the built-in's prod URL for every later\n * production deploy.\n */\nexport const BUILTIN_AGENTS_FOR_SEEDING: DiscoveredAgent[] =\n BUILTIN_AGENTS.filter((app) => app.url).map((app) => ({\n id: app.id,\n name: app.name,\n description: app.description,\n url: app.url, // ALWAYS prod\n color: app.color,\n }));\n"]}
|
|
1
|
+
{"version":3,"file":"agent-discovery.js","sourceRoot":"","sources":["../../src/server/agent-discovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAoBvE;;;;GAIG;AACH,MAAM,cAAc,GAAiB,gBAAgB,EAAE;KACpD,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC;KACxC,GAAG,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AC,WAAW;IAC5B,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,cAAc;IAC5B,KAAK,EAAE,GAAG,CAAC,KAAK;CACjB,CAAC,CAAC,CAAC","sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { TEMPLATES, visibleTemplates } from \"../cli/templates-meta.js\";\n\nexport interface DiscoveredAgent {\n id: string;\n name: string;\n description: string;\n url: string;\n color: string;\n}\n\ninterface AgentEntry {\n id: string;\n name: string;\n description: string;\n url: string;\n devUrl?: string;\n devPort: number;\n color: string;\n}\n\n/**\n * Built-in agent registry. Derive this from the published CLI metadata so\n * connected-agent discovery stays aligned with the public template allow-list\n * without depending on @agent-native/shared-app-config at runtime.\n */\nconst BUILTIN_AGENTS: AgentEntry[] = visibleTemplates()\n .filter((template) => !!template.prodUrl)\n .map((template) => ({\n id: template.name,\n name: template.label,\n description: template.description ?? template.hint,\n url: template.prodUrl!,\n devUrl: `http://localhost:${template.devPort}`,\n devPort: template.devPort,\n color: template.color,\n }));\n\nconst HIDDEN_FIRST_PARTY_AGENT_IDS = new Set(\n TEMPLATES.filter((template) => template.hidden && template.prodUrl).map(\n (template) => template.name,\n ),\n);\n\nconst WORKSPACE_APPS_ENV_KEY = \"AGENT_NATIVE_WORKSPACE_APPS_JSON\";\nconst WORKSPACE_APPS_MANIFEST_FILE = \"workspace-apps.json\";\n\ninterface WorkspaceAppManifestEntry {\n id: string;\n name: string;\n description: string;\n path: string;\n url?: string | null;\n isDispatch?: boolean;\n}\n\n/**\n * Get built-in agents (static, no DB). Used as fallback and for seeding.\n */\nexport function getBuiltinAgents(selfAppId?: string): DiscoveredAgent[] {\n return BUILTIN_AGENTS.filter((app) => app.id !== selfAppId && app.url).map(\n (app) => ({\n id: app.id,\n name: app.name,\n description: app.description,\n url: resolveAgentUrl(app),\n color: app.color,\n }),\n );\n}\n\n/**\n * Discover all agents: built-in + custom agents stored as resources.\n * Custom agents override built-in agents with the same ID.\n */\nexport async function discoverAgents(\n selfAppId?: string,\n): Promise<DiscoveredAgent[]> {\n const builtins = getBuiltinAgents(selfAppId);\n const agentsById = new Map<string, DiscoveredAgent>();\n\n // Start with built-ins\n for (const agent of builtins) {\n agentsById.set(agent.id, agent);\n }\n\n // Overlay custom agents from resources\n try {\n const { resourceList, resourceGet, SHARED_OWNER, resourceListAccessible } =\n await import(\"../resources/store.js\");\n const { DEV_MODE_USER_EMAIL } = await import(\"./auth.js\");\n\n const isDevMode =\n typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\";\n\n const { parseRemoteAgentManifest, REMOTE_AGENT_RESOURCE_PREFIXES } =\n await import(\"../resources/metadata.js\");\n\n const resources: Array<{ id: string; path: string }> = [];\n for (const prefix of [...REMOTE_AGENT_RESOURCE_PREFIXES].reverse()) {\n resources.push(\n ...(isDevMode\n ? await resourceListAccessible(DEV_MODE_USER_EMAIL, prefix)\n : await resourceList(SHARED_OWNER, prefix)),\n );\n }\n\n for (const r of resources) {\n if (!r.path.endsWith(\".json\")) continue;\n try {\n const full = await resourceGet(r.id);\n if (!full) continue;\n const manifest = parseRemoteAgentManifest(full.content, r.path);\n if (!manifest || manifest.id === selfAppId) continue;\n if (HIDDEN_FIRST_PARTY_AGENT_IDS.has(manifest.id)) continue;\n\n // If the resource override carries a localhost URL but we're running\n // in production (e.g. a stale dev-time seed got promoted to the prod\n // DB), fall back to the matching built-in's prod URL instead of\n // letting the override win — otherwise outbound `call-agent` fetches\n // from a serverless function would target localhost and fail with\n // \"fetch failed\" instantly. The override still wins for non-localhost\n // URLs (the supported case for self-hosted custom agents).\n let url = manifest.url;\n if (\n !isDevMode &&\n typeof url === \"string\" &&\n /^https?:\\/\\/(localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0)(:|\\/|$)/.test(url)\n ) {\n const builtin = agentsById.get(manifest.id);\n if (builtin?.url) url = builtin.url;\n }\n\n agentsById.set(manifest.id, {\n id: manifest.id,\n name: manifest.name,\n description: manifest.description || \"\",\n url,\n color: manifest.color || \"#6B7280\",\n });\n } catch {\n // Skip unreadable resources\n }\n }\n } catch {\n // Resources not available — use built-ins only\n }\n\n // Overlay sibling workspace apps last so same-origin workspaces prefer the\n // app mounted in this workspace over the public template with the same id.\n for (const agent of discoverWorkspaceAgents(selfAppId)) {\n agentsById.set(agent.id, agent);\n }\n\n return Array.from(agentsById.values());\n}\n\n/**\n * Look up a single agent by ID or name (case-insensitive).\n */\nexport async function findAgent(\n idOrName: string,\n selfAppId?: string,\n): Promise<DiscoveredAgent | undefined> {\n const lower = idOrName.toLowerCase();\n const agents = await discoverAgents(selfAppId);\n return agents.find((a) => a.id === lower || a.name.toLowerCase() === lower);\n}\n\nfunction isDevEnvironment(): boolean {\n return (\n typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\"\n );\n}\n\nfunction resolveAgentUrl(app: AgentEntry): string {\n if (isDevEnvironment()) {\n return app.devUrl || `http://localhost:${app.devPort}`;\n }\n return app.url;\n}\n\nfunction readJson(file: string): any {\n try {\n return JSON.parse(fs.readFileSync(file, \"utf8\"));\n } catch {\n return null;\n }\n}\n\nfunction findWorkspaceRoot(startDir = process.cwd()): string | null {\n let dir = path.resolve(startDir);\n for (let i = 0; i < 20; i++) {\n const pkg = readJson(path.join(dir, \"package.json\"));\n if (typeof pkg?.[\"agent-native\"]?.workspaceCore === \"string\") {\n return dir;\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\nfunction titleCase(value: string): string {\n return value\n .split(/[-_\\s]+/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(\" \");\n}\n\nfunction parseWorkspaceAppsManifest(\n parsed: any,\n): WorkspaceAppManifestEntry[] | null {\n const rawApps = Array.isArray(parsed?.apps)\n ? parsed.apps\n : Array.isArray(parsed)\n ? parsed\n : null;\n if (!rawApps) return null;\n\n const apps = rawApps\n .map((entry) => {\n if (!entry || typeof entry !== \"object\") return null;\n const id = typeof entry.id === \"string\" ? entry.id.trim() : \"\";\n const pathValue = typeof entry.path === \"string\" ? entry.path.trim() : \"\";\n if (!id || !pathValue.startsWith(\"/\")) return null;\n return {\n id,\n name:\n typeof entry.name === \"string\" && entry.name.trim()\n ? entry.name.trim()\n : titleCase(id),\n description:\n typeof entry.description === \"string\" ? entry.description : \"\",\n path: pathValue,\n url:\n typeof entry.url === \"string\" && entry.url.trim()\n ? entry.url.trim()\n : null,\n isDispatch:\n typeof entry.isDispatch === \"boolean\"\n ? entry.isDispatch\n : id === \"dispatch\",\n } satisfies WorkspaceAppManifestEntry;\n })\n .filter((app): app is WorkspaceAppManifestEntry => !!app)\n .sort((a, b) => {\n if (a.id === \"dispatch\") return -1;\n if (b.id === \"dispatch\") return 1;\n return a.name.localeCompare(b.name);\n });\n\n return apps.length ? apps : null;\n}\n\nfunction readWorkspaceAppsFromEnv(): WorkspaceAppManifestEntry[] | null {\n const raw = process.env[WORKSPACE_APPS_ENV_KEY];\n if (!raw) return null;\n try {\n return parseWorkspaceAppsManifest(JSON.parse(raw));\n } catch {\n return null;\n }\n}\n\nfunction workspaceAppsManifestCandidates(): string[] {\n const candidates: string[] = [];\n try {\n candidates.push(\n path.join(process.cwd(), \".agent-native\", WORKSPACE_APPS_MANIFEST_FILE),\n path.join(process.cwd(), WORKSPACE_APPS_MANIFEST_FILE),\n );\n } catch {\n // Some edge runtimes do not expose process.cwd().\n }\n try {\n const moduleDir = path.dirname(fileURLToPath(import.meta.url));\n candidates.push(\n path.join(moduleDir, \".agent-native\", WORKSPACE_APPS_MANIFEST_FILE),\n path.join(moduleDir, WORKSPACE_APPS_MANIFEST_FILE),\n );\n } catch {\n // Some edge runtimes expose non-file module URLs. The env manifest still\n // works there, so skip file-relative candidates.\n }\n return candidates;\n}\n\nfunction readWorkspaceAppsFromManifestFile():\n | WorkspaceAppManifestEntry[]\n | null {\n for (const file of workspaceAppsManifestCandidates()) {\n if (!fs.existsSync(file)) continue;\n const apps = parseWorkspaceAppsManifest(readJson(file));\n if (apps) return apps;\n }\n return null;\n}\n\nfunction readWorkspaceAppsFromFilesystem(): WorkspaceAppManifestEntry[] | null {\n const workspaceRoot = findWorkspaceRoot();\n if (!workspaceRoot) return null;\n const appsDir = path.join(workspaceRoot, \"apps\");\n if (!fs.existsSync(appsDir)) return null;\n\n const apps = fs\n .readdirSync(appsDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry): WorkspaceAppManifestEntry | null => {\n const appDir = path.join(appsDir, entry.name);\n const pkg = readJson(path.join(appDir, \"package.json\"));\n if (!pkg) return null;\n return {\n id: entry.name,\n name: pkg.displayName || titleCase(entry.name),\n description: pkg.description || \"\",\n path: `/${entry.name}`,\n isDispatch: entry.name === \"dispatch\",\n } satisfies WorkspaceAppManifestEntry;\n })\n .filter((app): app is WorkspaceAppManifestEntry => !!app)\n .sort((a, b) => {\n if (a.id === \"dispatch\") return -1;\n if (b.id === \"dispatch\") return 1;\n return a.name.localeCompare(b.name);\n });\n\n return apps.length ? apps : null;\n}\n\nfunction workspaceBaseUrl(): string | null {\n return (\n process.env.WORKSPACE_GATEWAY_URL ||\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n process.env.BETTER_AUTH_URL ||\n null\n );\n}\n\nfunction workspaceAppUrl(app: WorkspaceAppManifestEntry): string | null {\n if (app.url) return app.url;\n const base = workspaceBaseUrl();\n if (!base) return null;\n try {\n return new URL(app.path, `${base.replace(/\\/$/, \"\")}/`).toString();\n } catch {\n return null;\n }\n}\n\nfunction discoverWorkspaceAgents(selfAppId?: string): DiscoveredAgent[] {\n const workspaceApps =\n readWorkspaceAppsFromEnv() ??\n readWorkspaceAppsFromManifestFile() ??\n readWorkspaceAppsFromFilesystem();\n if (!workspaceApps) return [];\n\n return workspaceApps\n .filter((app) => app.id !== selfAppId)\n .map((app) => {\n const url = workspaceAppUrl(app);\n if (!url) return null;\n const builtin = BUILTIN_AGENTS.find((agent) => agent.id === app.id);\n return {\n id: app.id,\n name: app.name,\n description:\n app.description ||\n builtin?.description ||\n `Workspace app mounted at ${app.path}`,\n url,\n color: builtin?.color || \"#6B7280\",\n } satisfies DiscoveredAgent;\n })\n .filter((agent): agent is DiscoveredAgent => !!agent);\n}\n\n/**\n * Like `getBuiltinAgents`, but always returns the production URL — never the\n * env-resolved devUrl. Used by the resource seeder so that a one-time seed\n * (`ON CONFLICT DO NOTHING`) can't permanently bake a localhost URL into the\n * DB, which would override the built-in's prod URL for every later\n * production deploy.\n */\nexport const BUILTIN_AGENTS_FOR_SEEDING: DiscoveredAgent[] =\n BUILTIN_AGENTS.filter((app) => app.url).map((app) => ({\n id: app.id,\n name: app.name,\n description: app.description,\n url: app.url, // ALWAYS prod\n color: app.color,\n }));\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/server/auth.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAClC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gCAAgC,CAAC;AAsChE,KAAK,KAAK,GAAG,SAAS,CAAC;AASvB,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAuBlE;;;GAGG;AACH,wBAAgB,gBAAgB,IAAI,MAAM,CAEzC;AAMD,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,mFAAmF;IACnF,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,oEAAoE;IACpE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,kEAAkE;IAClE,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,WAAW;IAC1B,mDAAmD;IACnD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,UAAU,CAAC,EAAE,CAA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,CAAC,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAeD,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,QAWd;AAED,wBAAgB,uBAAuB,CACrC,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,2BAA2B,QAOnC;AAmGD;;;;;;GAMG;AACH,wBAAsB,YAAY,CAChC,KAAK,EAAE,OAAO,GACb,OAAO,CAAC,QAAQ,GAAG,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC,CAG5C;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,mBAAmB,oBAAoB,CAAC;AAuPrD;;;;;;;;;;;;GAYG;AACH,wBAAsB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CAwI5E;AA+tCD;;;;;;;;;;;;GAYG;AACH,wBAAsB,aAAa,CACjC,GAAG,EAAE,KAAK,EACV,OAAO,GAAE,WAAgB,GACxB,OAAO,CAAC,OAAO,CAAC,CA+KlB;AAMD;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,GAAG,IAAI,CAEzE"}
|
package/dist/server/auth.js
CHANGED
|
@@ -575,6 +575,12 @@ function createAuthGuardFn() {
|
|
|
575
575
|
if (p === "/_agent-native/integrations/process-task") {
|
|
576
576
|
return;
|
|
577
577
|
}
|
|
578
|
+
// Internal processor endpoint for deferred A2A continuations created by
|
|
579
|
+
// integration tasks. It uses the same HMAC internal-token scheme as the
|
|
580
|
+
// primary integration processor, so it must bypass cookie/session auth.
|
|
581
|
+
if (p === "/_agent-native/integrations/process-a2a-continuation") {
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
578
584
|
// A2A endpoint verifies authenticity via JWT signed with the org's A2A
|
|
579
585
|
// secret (or the global A2A_SECRET fallback), not via session cookies.
|
|
580
586
|
if (p === "/_agent-native/a2a") {
|