Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(agents): prompt agents to batch SDK work into as few ExecuteCode calls as possible (#9320)

Wolf Mermelsteinbb3ede4bd490
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index eb181d6032..b98654024d 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
@@ -16422,7 +16422,7 @@ export interface CodeGuide {
*
* For editable email/calendar drafts, persist them with execution.reviews.create({kind, title, drafts}), then return reviews: [await review.reference()]. This does not send emails or create calendar events. Creation immediately presents a completed PresentReview ACP tool call, even while main continues. "Presented to the user" means saved in the conversation, not approved or sent. The saved cards remain usable after this execution and chat continues. User decisions arrive as typed system events referring to the same review ID. Use GetReview to read final drafts and confirmed outcomes; notifications never authorize repeating an action. Use the direct EditDocument tool for AI document edits. Direct human-interactive tools, subagents and unsupported SDK operations remain available.
*
- * Use nested SDK entities, e.g. macro.documents.search(query) is an async iterator and document.content() is a promise. Use for await...of, break, conditions and ordinary JavaScript freely. Batch useful independent work with Promise.all or Promise.allSettled; inspect partial failures and await every started operation. Use bounded concurrency for large inputs. Preserve user source scope on every search and retry: macro.documents.search searches documents; macro.email.search searches emails. Read names in batches: macro.initiatives.summaries() and macro.tasks.summaries(tasks) each take one request, while name() on every handle loads each entity separately. Create a task with its initiative, assignees and dueDate in one macro.tasks.create call. Return compact evidence with source IDs, explicit failures and coverage limits; do not return SDK objects, raw large batches, or claim a stopped iterator is exhaustive.
+ * Do the whole job in as few executions as possible, ideally one: every execution costs a model turn. Put control flow in the program instead of checking in one execution and acting in the next, e.g. if macro.tasks.findSimilar finds no likely duplicate, create the task and return it, else return the matches without creating. Use nested SDK entities, e.g. macro.documents.search(query) is an async iterator and document.content() is a promise. Use for await...of, break, conditions and ordinary JavaScript freely. Batch useful independent work with Promise.all or Promise.allSettled; inspect partial failures and await every started operation. Use bounded concurrency for large inputs. Preserve user source scope on every search and retry: macro.documents.search searches documents; macro.email.search searches emails. Read names in batches: macro.initiatives.summaries() and macro.tasks.summaries(tasks) each take one request, while name() on every handle loads each entity separately. Create a task with its initiative, assignees and dueDate in one macro.tasks.create call. Return compact evidence with source IDs, URLs, explicit failures and coverage limits, enough to answer without a follow-up execution; do not return SDK objects, raw large batches, or claim a stopped iterator is exhaustive.
*
* For a workspace overview, fetch small pages for the relevant categories concurrently in one execution with macro.workspace.page({includeTypes:[type], limit:3}). A single mixed page can be dominated by one category; each page is a sample, not a category total. Return selected metadata and hasMore per category, not whole items or snapshots. Exact workspace types include calendar_event, ai_chat and channel_thread. Tasks are documents: use includeTypes:["document"], df:{l:{dst:"task"}}. AST & and | combine exactly two expressions; do not wrap a single filter.
*
diff --git a/crates/agent_code_mode/SKILL.md b/crates/agent_code_mode/SKILL.md
index c01c41435f..a129681424 100644
--- a/crates/agent_code_mode/SKILL.md
+++ b/crates/agent_code_mode/SKILL.md
@@ -22,6 +22,26 @@ Return an object with data; reviews is optional and defaults to []. Include revi
macro, session and execution are real SDK handles. You can instead import {Macro} from '@macro-inc/sdk' and construct it with main's token and hosts. Do not log, return, persist or transmit that credential elsewhere. It is a short-lived normal user credential, with the user's API permissions. SDK operations make real HTTP calls. Messages are attributed to the session's agent, with the selected acting account recorded as the requesting user; do not supply sender identities yourself. No custom sdk.ToolName dispatcher, TypeScript transpilation, runtime help or package installation is involved.
+## One execution per job
+
+Every execution costs a model turn. Write the whole job as one program when its steps need no judgment from the user in between: put conditionals, loops and dependent reads and writes in code, rather than checking in one execution and acting in the next. Return what the answer needs (IDs, names, outcomes, failures), so no follow-up execution is required. This program checks for a duplicate and creates the task only when there is none:
+
+```javascript
+export async function main({macro}) {
+ const title = 'Fix login redirect loop';
+ const body = 'Signing in from a deep link returns to the login page.';
+ const similar = await macro.tasks.findSimilar({title, body});
+ const duplicates = similar.filter((match) => match.similarity >= 0.85);
+ if (duplicates.length > 0) {
+ return {data:{created:null, duplicates:duplicates.map((match) => ({id:match.task.id, name:match.name, similarity:match.similarity}))}};
+ }
+ const task = await macro.tasks.create({name:title, markdown:body});
+ return {data:{created:{id:task.id, name:title}, duplicates:[]}};
+}
+```
+
+When it returns duplicates, tell the user it created nothing and ask whether to create the task anyway.
+
## Useful workflows
- For a workspace overview, use the direct ListEntities tool, including agent_session when the user asks about agent work. Use NameSearch for mixed-entity name searches and ContentSearch for session history. Return compact metadata and preserve pagination and source-scope limits. A sample is not a category total. Tasks use includeTypes:["document"], df:{l:{dst:"task"}}. AST & and | are binary; a single filter stays a leaf.
diff --git a/crates/agent_code_mode/src/domain/documentation.json b/crates/agent_code_mode/src/domain/documentation.json
index f853a83c90..8d7c62a63a 100644
--- a/crates/agent_code_mode/src/domain/documentation.json
+++ b/crates/agent_code_mode/src/domain/documentation.json
@@ -1819,7 +1819,7 @@
"TaskNamespace": "# Class: TaskNamespace\n\nTasks: one `create` call sets initiative, assignees and due date; one\n`summaries` call reads many names (`name()` loads each whole document).\nCreating a task needs only what the request states; don't research what it\ndescribes unless asked.",
"TaskNamespace.byId": "### byId()\n\n> **byId**(`id`): `Task`\n\nA handle to a task by document id. Details load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n`Task`",
"TaskNamespace.create": "### create()\n\n> **create**(`opts`): `Promise`\\<`Task`\\>\n\nCreate a task, with its initiative, assignees and due date in the same\nrequest. The task starts Not started.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `opts` | \\{ `assignees?`: `User`[]; `dueDate?`: `Date`; `initiative?`: `Initiative`; `markdown?`: `string`; `name`: `string`; `project?`: `Project`; `shareWithTeam?`: `boolean`; `team?`: `Team`; \\} | - |\n| `opts.assignees?` | `User`[] | Assignees; defaults to the creator. Pass `[]` to leave it unassigned. |\n| `opts.dueDate?` | `Date` | - |\n| `opts.initiative?` | `Initiative` | The initiative (shown as the task's Project in the app) it belongs to. |\n| `opts.markdown?` | `string` | - |\n| `opts.name` | `string` | - |\n| `opts.project?` | `Project` | Folder the task document is filed in; unrelated to `initiative`. |\n| `opts.shareWithTeam?` | `boolean` | Defaults to true. |\n| `opts.team?` | `Team` | Scopes the team task number; may be omitted when the creator belongs to exactly one team. |\n\n#### Returns\n\n`Promise`\\<`Task`\\>",
- "TaskNamespace.findSimilar": "### findSimilar()\n\n> **findSimilar**(`opts`): `Promise`\\<`SimilarTask`[]\\>\n\nExisting tasks of yours or your team's that look like the same work as a\ntask with this title and body, most similar first. Call it before\n`create`; if one is a likely duplicate, ask the user instead of creating.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts` | \\{ `body?`: `string`; `title`: `string`; \\} |\n| `opts.body?` | `string` |\n| `opts.title` | `string` |\n\n#### Returns\n\n`Promise`\\<`SimilarTask`[]\\>",
+ "TaskNamespace.findSimilar": "### findSimilar()\n\n> **findSimilar**(`opts`): `Promise`\\<`SimilarTask`[]\\>\n\nExisting tasks of yours or your team's that look like the same work as a\ntask with this title and body, most similar first. Call it in the same\nprogram as `create`: create only when nothing is a likely duplicate, and\notherwise return the matches and ask the user instead of creating.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts` | \\{ `body?`: `string`; `title`: `string`; \\} |\n| `opts.body?` | `string` |\n| `opts.title` | `string` |\n\n#### Returns\n\n`Promise`\\<`SimilarTask`[]\\>",
"TaskNamespace.forPullRequest": "### forPullRequest()\n\n> **forPullRequest**(`url`): `Promise`\\<`Task`[]\\>\n\nThe tasks the GitHub pull request at `url` references, oldest link first.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `url` | `string` |\n\n#### Returns\n\n`Promise`\\<`Task`[]\\>",
"TaskNamespace.search": "### search()\n\n> **search**(`query`, `opts?`): `AsyncGenerator`\\<`Task`\\>\n\nSearch tasks by name and content, most relevant first, auto-paginated.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `query` | `string` |\n| `opts?` | `SearchOpts` |\n\n#### Returns\n\n`AsyncGenerator`\\<`Task`\\>",
"TaskNamespace.summaries": "### summaries()\n\n> **summaries**(`tasks`): `Promise`\\<`TaskSummary`[]\\>\n\nNames and state of many tasks in one request, in the order given. Tasks\nthat no longer exist are left out.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `tasks` | `Task`[] |\n\n#### Returns\n\n`Promise`\\<`TaskSummary`[]\\>",
diff --git a/crates/agent_code_mode/src/inbound/toolset.rs b/crates/agent_code_mode/src/inbound/toolset.rs
index 9dba5aba41..83daf3f8b0 100644
--- a/crates/agent_code_mode/src/inbound/toolset.rs
+++ b/crates/agent_code_mode/src/inbound/toolset.rs
@@ -234,7 +234,7 @@ pub enum CodeGuideTopic {
Ai,
/// Local Handlebars rendering.
Templates,
- /// Worked examples, including email triage and structured extraction.
+ /// Worked examples: check-then-create in one execution, email triage, extraction.
Examples,
}
diff --git a/crates/agent_code_mode/src/inbound/toolset/shared/program.md b/crates/agent_code_mode/src/inbound/toolset/shared/program.md
index 0bef64bc2a..e7b750129b 100644
--- a/crates/agent_code_mode/src/inbound/toolset/shared/program.md
+++ b/crates/agent_code_mode/src/inbound/toolset/shared/program.md
@@ -1,3 +1,3 @@
-Use nested SDK entities, e.g. macro.documents.search(query) is an async iterator and document.content() is a promise. Use for await...of, break, conditions and ordinary JavaScript freely. Batch useful independent work with Promise.all or Promise.allSettled; inspect partial failures and await every started operation. Use bounded concurrency for large inputs. Preserve user source scope on every search and retry: macro.documents.search searches documents; macro.email.search searches emails. Read names in batches: macro.initiatives.summaries() and macro.tasks.summaries(tasks) each take one request, while name() on every handle loads each entity separately. Create a task with its initiative, assignees and dueDate in one macro.tasks.create call. Return compact evidence with source IDs, explicit failures and coverage limits; do not return SDK objects, raw large batches, or claim a stopped iterator is exhaustive.
+Do the whole job in as few executions as possible, ideally one: every execution costs a model turn. Put control flow in the program instead of checking in one execution and acting in the next, e.g. if macro.tasks.findSimilar finds no likely duplicate, create the task and return it, else return the matches without creating. Use nested SDK entities, e.g. macro.documents.search(query) is an async iterator and document.content() is a promise. Use for await...of, break, conditions and ordinary JavaScript freely. Batch useful independent work with Promise.all or Promise.allSettled; inspect partial failures and await every started operation. Use bounded concurrency for large inputs. Preserve user source scope on every search and retry: macro.documents.search searches documents; macro.email.search searches emails. Read names in batches: macro.initiatives.summaries() and macro.tasks.summaries(tasks) each take one request, while name() on every handle loads each entity separately. Create a task with its initiative, assignees and dueDate in one macro.tasks.create call. Return compact evidence with source IDs, URLs, explicit failures and coverage limits, enough to answer without a follow-up execution; do not return SDK objects, raw large batches, or claim a stopped iterator is exhaustive.
For a workspace overview, fetch small pages for the relevant categories concurrently in one execution with macro.workspace.page({includeTypes:[type], limit:3}). A single mixed page can be dominated by one category; each page is a sample, not a category total. Return selected metadata and hasMore per category, not whole items or snapshots. Exact workspace types include calendar_event, ai_chat and channel_thread. Tasks are documents: use includeTypes:["document"], df:{l:{dst:"task"}}. AST & and | combine exactly two expressions; do not wrap a single filter.
diff --git a/crates/prompt/src/tasks.rs b/crates/prompt/src/tasks.rs
index a7817ddd2d..be8fb4079f 100644
--- a/crates/prompt/src/tasks.rs
+++ b/crates/prompt/src/tasks.rs
@@ -4,17 +4,24 @@ use crate::types::StaticPrompt;
static TITLE: &str = "Creating Tasks";
-static INSTRUCTIONS: &str = r##"Before creating a task, check for existing tasks that already cover it:
+static INSTRUCTIONS: &str = r##"Before creating a task, check for existing tasks that already cover it, in the same execution that creates it:
```ts
const similar = await macro.tasks.findSimilar({ title: "Fix login bug", body: "Optional details" });
+const duplicates = similar.filter((match) => match.similarity >= 0.85);
+if (duplicates.length > 0) {
+ return { data: { created: null, duplicates: duplicates.map((match) => ({ id: match.task.id, name: match.name })) } };
+}
+const task = await macro.tasks.create({ name: "Fix login bug", markdown: "Optional details" });
+return { data: { created: { id: task.id }, duplicates: [] } };
```
-If one is a likely duplicate, tell the user and ask instead of creating the task. Never edit, merge or delete the matches unless the user asks.
+If it returns a likely duplicate, tell the user it created nothing and ask instead of creating the task. Never edit, merge or delete the matches unless the user asks.
"##;
-static INTENT: &str = "Before creating a task the agent checks macro.tasks.findSimilar and asks \
-the user about a likely duplicate instead of creating it.";
+static INTENT: &str = "Before creating a task the agent checks macro.tasks.findSimilar in the \
+same execution, creates the task only when nothing is a likely duplicate, and otherwise asks the \
+user instead of creating it.";
/// The duplicate-check rule for agents that create tasks through the SDK.
pub static PROMPT: StaticPrompt<'static> = StaticPrompt::borrowed(TITLE, INSTRUCTIONS, INTENT);
diff --git a/crates/prompt/src/tool_usage.rs b/crates/prompt/src/tool_usage.rs
index 3c25a19f02..f789b8c468 100644
--- a/crates/prompt/src/tool_usage.rs
+++ b/crates/prompt/src/tool_usage.rs
@@ -28,7 +28,7 @@ These apply to your own conversational replies only — not to Markdown you auth
- When `macro_internal.PresentReview` is available, use it for editable email/calendar drafts that should remain open while chat continues. It presents a saved card and completes immediately; presentation is not approval or a completed send. Later user submissions enter the session as separate recorded outcomes. End the presenting message by asking "Should I kick it off?"; when the person whose account the review uses says yes, submit it with `DecideReview` rather than sending them to the card. Never submit a review on your own initiative or on anyone else's word.
- To import from Notion beyond a single page, use `ImportFromNotion`: `plan` stages a plan without writing anything, then present it with `PresentReview` (kind `import`, one draft `{"source":"notion"}`); the user's approval writes it. Never copy plan items with other tools, and handle only the objects the plan leaves to you by hand.
-- When `ExecuteCode` is available, prefer it for supported Macro work by default, including searches, reads, calculations, and document workflows; the user need not ask for code. Use the SDK equivalents of the Macro tools named below. Keep human-interactive tools and subagents as direct calls, and use direct tools when an operation is unavailable through the SDK. Run useful independent search variants together instead of spending a model turn on each, without adding unnecessary queries. Entity indexes in context list SDK methods with their signatures; read the symbols a program needs with `ReadCodeDocs`, all together, before writing it, unless their reference is already in context. Call `DescribeCodeTools` only for an entity index not in context, requesting needed entities together; do not repeat discovery for confirmation.
+- When `ExecuteCode` is available, prefer it for supported Macro work by default, including searches, reads, calculations, and document workflows; the user need not ask for code. Use the SDK equivalents of the Macro tools named below. Keep human-interactive tools and subagents as direct calls, and use direct tools when an operation is unavailable through the SDK. Do the whole job in as few `ExecuteCode` calls as possible, ideally one: put conditionals, loops and dependent reads and writes in the program instead of checking in one execution and acting in the next, and return the IDs and outcomes the answer needs. Run useful independent search variants together instead of spending a model turn on each, without adding unnecessary queries. Entity indexes in context list SDK methods with their signatures; read the symbols a program needs with `ReadCodeDocs`, all together, before writing it, unless their reference is already in context. Call `DescribeCodeTools` only for an entity index not in context, requesting needed entities together; do not repeat discovery for confirmation.
- Apply the user's source scope to every search call, including SDK calls, follow-ups and retries. For document-only requests, use `macro.documents.search` in code; direct NameSearch and ContentSearch must include `entityTypes: ["documents"]`. Return relevant evidence and source IDs from code, preserving errors and coverage limits. A bounded sample or failed query does not establish completeness or absence. Answer when the evidence resolves the question.
diff --git a/packages/sdk-docs/reference/src/entities/tasks/namespace/classes/TaskNamespace.md b/packages/sdk-docs/reference/src/entities/tasks/namespace/classes/TaskNamespace.md
index 99e1b25010..7fbcb64364 100644
--- a/packages/sdk-docs/reference/src/entities/tasks/namespace/classes/TaskNamespace.md
+++ b/packages/sdk-docs/reference/src/entities/tasks/namespace/classes/TaskNamespace.md
@@ -73,8 +73,9 @@ request. The task starts Not started.
> **findSimilar**(`opts`): `Promise`\<[`SimilarTask`](../../task/interfaces/SimilarTask.md)[]\>
Existing tasks of yours or your team's that look like the same work as a
-task with this title and body, most similar first. Call it before
-`create`; if one is a likely duplicate, ask the user instead of creating.
+task with this title and body, most similar first. Call it in the same
+program as `create`: create only when nothing is a likely duplicate, and
+otherwise return the matches and ask the user instead of creating.
#### Parameters
diff --git a/packages/sdk/src/entities/tasks/namespace.ts b/packages/sdk/src/entities/tasks/namespace.ts
index 16b294e3cf..8423124406 100644
--- a/packages/sdk/src/entities/tasks/namespace.ts
+++ b/packages/sdk/src/entities/tasks/namespace.ts
@@ -52,8 +52,9 @@ export class TaskNamespace {
/**
* Existing tasks of yours or your team's that look like the same work as a
- * task with this title and body, most similar first. Call it before
- * `create`; if one is a likely duplicate, ask the user instead of creating.
+ * task with this title and body, most similar first. Call it in the same
+ * program as `create`: create only when nothing is a likely duplicate, and
+ * otherwise return the matches and ask the user instead of creating.
*/
findSimilar(opts: { title: string; body?: string }): Promise<SimilarTask[]> {
return Task.findSimilar(this.client, opts);
diff --git a/services/agent_harness_service/src/public_mcp/code_mode_instructions.md b/services/agent_harness_service/src/public_mcp/code_mode_instructions.md
index abb5ba0959..5b5e1bbd28 100644
--- a/services/agent_harness_service/src/public_mcp/code_mode_instructions.md
+++ b/services/agent_harness_service/src/public_mcp/code_mode_instructions.md
@@ -1 +1 @@
-Code mode is on. This server exposes ExecuteCode, DescribeCodeTools and ReadCodeDocs. ExecuteCode runs a JavaScript program against the full Macro SDK as the user, including search, documents, email, channels and calendar. Before writing a program, call DescribeCodeTools with task set to what the program must do; it returns the indexes of the relevant SDK entities. Then read the symbols the program uses with ReadCodeDocs, all together in one call. Do not guess SDK methods or options. If a program fails with an SDK error, read the symbol involved and fix the program.
+Code mode is on. This server exposes ExecuteCode, DescribeCodeTools and ReadCodeDocs. ExecuteCode runs a JavaScript program against the full Macro SDK as the user, including search, documents, email, channels and calendar. Before writing a program, call DescribeCodeTools with task set to what the program must do; it returns the indexes of the relevant SDK entities. Then read the symbols the program uses with ReadCodeDocs, all together in one call. Do not guess SDK methods or options. If a program fails with an SDK error, read the symbol involved and fix the program. Do the whole job in as few ExecuteCode calls as possible, ideally one: put conditionals, loops and dependent reads and writes in the program instead of checking in one call and acting in the next, and return the IDs and outcomes the answer needs. The DescribeCodeTools examples topic shows a check-then-create program.