Skip to content

Build and run agents you can see, understand and trust.

perf(prompt): improve instructions for workspace, context compression and the CreateTask tool (#2111)

DavdGao614085ecd5b3
diff --git a/src/agentscope/agent/_config.py b/src/agentscope/agent/_config.py
index ad9cf92ee..b9e6e55bd 100644
--- a/src/agentscope/agent/_config.py
+++ b/src/agentscope/agent/_config.py
@@ -70,7 +70,26 @@ class ContextConfig(BaseModel):
"Now write a continuation summary that will allow you to resume "
"work efficiently in a future context window where the "
"conversation history will be replaced with this summary. "
- "Your summary should be structured, concise, and actionable."
+ "Your summary should be structured, concise, and actionable.\n"
+ "The current time is {current_time}.\n"
+ "This summary may itself be summarized again later, and the "
+ "conversation history it refers to will be gone, so every "
+ "reference must be self-contained — resolve anything that "
+ "depends on the vanished context into an absolute, "
+ "fully-qualified form:\n"
+ "- Time: convert relative expressions ('today', 'now', "
+ "'yesterday', 'tomorrow', 'recently') to absolute dates using "
+ "the current time above; re-anchor them even if an earlier "
+ "summary already wrote them relatively.\n"
+ "- Names & pointers: use file paths, symbol names, PR/issue "
+ "numbers, IDs, URLs, and exact commands/error strings verbatim "
+ "instead of 'this file', 'the above', 'the second approach', "
+ "'the 5 failing tests'.\n"
+ "- In-flight work: record everything still pending, especially "
+ "tools launched in the background whose results you are still "
+ "waiting on — give each one's id and a short note of what it is "
+ "doing — and mark each item's owner (user request vs your own "
+ "decision) and status (done / pending / blocked).\n"
"</system-hint>"
),
# ``format: textarea`` is a hint for schema-driven UI renderers
diff --git a/src/agentscope/middleware/_longterm_memory/_agentic_memory/_middleware.py b/src/agentscope/middleware/_longterm_memory/_agentic_memory/_middleware.py
index 255b22b05..135ff463f 100644
--- a/src/agentscope/middleware/_longterm_memory/_agentic_memory/_middleware.py
+++ b/src/agentscope/middleware/_longterm_memory/_agentic_memory/_middleware.py
@@ -43,131 +43,281 @@ class _MemoryFileHeader:
DEFAULT_MEMORY_INSTRUCTIONS = """# Auto Memory
-You have a persistent, file-based memory system at `{memory_dir}`. This directory already exists — write to it directly with the `Write` tool (do not run mkdir or check for its existence).
+You have a persistent, file-based memory system at `{memory_dir}`. \
+This directory already exists — write to it directly with the `Write` \
+tool (do not run mkdir or check for its existence).
-You should build up this memory system over time so that future conversations can have a complete picture of who the user is, how they'd like to collaborate with you, what behaviors to avoid or repeat, and the context behind the work the user gives you.
+You should build up this memory system over time so that future \
+conversations can have a complete picture of who the user is, \
+how they'd like to collaborate with you, what behaviors to avoid or repeat, \
+and the context behind the work the user gives you.
-If the user explicitly asks you to remember something, save it immediately as whichever type fits best. If they ask you to forget something, find and remove the relevant entry.
+If the user explicitly asks you to remember something, save it immediately \
+as whichever type fits best. If they ask you to forget something, \
+find and remove the relevant entry.
## Types of memory
-There are several discrete types of memory that you can store in your memory system:
+There are several discrete types of memory that you can store in your \
+memory system:
<types>
<type>
<name>user</name>
- <description>Contain information about the user's role, goals, responsibilities, and knowledge. Great user memories help you tailor your future behavior to the user's preferences and perspective. Your goal in reading and writing these memories is to build up an understanding of who the user is and how you can be most helpful to them specifically. For example, you should collaborate with a senior software engineer differently than a student who is coding for the very first time. Keep in mind, that the aim here is to be helpful to the user. Avoid writing memories about the user that could be viewed as a negative judgement or that are not relevant to the work you're trying to accomplish together.</description>
- <when_to_save>When you learn any details about the user's role, preferences, responsibilities, or knowledge</when_to_save>
- <how_to_use>When your work should be informed by the user's profile or perspective. For example, if the user is asking you to explain a part of the code, you should answer that question in a way that is tailored to the specific details that they will find most valuable or that helps them build their mental model in relation to domain knowledge they already have.</how_to_use>
+ <description>Contain information about the user's role, goals, \
+responsibilities, and knowledge. Great user memories help you tailor your \
+future behavior to the user's preferences and perspective. Your goal in \
+reading and writing these memories is to build up an understanding of who \
+the user is and how you can be most helpful to them specifically. \
+For example, you should collaborate with a senior software engineer \
+differently than a student who is coding for the very first time. \
+Keep in mind, that the aim here is to be helpful to the user. \
+Avoid writing memories about the user that could be viewed as a negative \
+judgement or that are not relevant to the work you're trying to \
+accomplish together.</description>
+ <when_to_save>When you learn any details about the user's role, \
+preferences, responsibilities, or knowledge</when_to_save>
+ <how_to_use>When your work should be informed by the user's profile or \
+perspective. For example, if the user is asking you to explain a part of the \
+code, you should answer that question in a way that is tailored to the \
+specific details that they will find most valuable or that helps them build \
+their mental model in relation to domain knowledge they already have.\
+</how_to_use>
<examples>
user: I'm a data scientist investigating what logging we have in place
- assistant: [saves user memory: user is a data scientist, currently focused on observability/logging]
+ assistant: [saves user memory: user is a data scientist, currently \
+focused on observability/logging]
- user: I've been writing Go for ten years but this is my first time touching the React side of this repo
- assistant: [saves user memory: deep Go expertise, new to React and this project's frontend — frame frontend explanations in terms of backend analogues]
+ user: I've been writing Go for ten years but this is my first time \
+touching the React side of this repo
+ assistant: [saves user memory: deep Go expertise, new to React and this \
+project's frontend — frame frontend explanations in terms of backend analogues]
</examples>
</type>
<type>
<name>feedback</name>
- <description>Guidance the user has given you about how to approach work — both what to avoid and what to keep doing. These are a very important type of memory to read and write as they allow you to remain coherent and responsive to the way you should approach work in the project. Record from failure AND success: if you only save corrections, you will avoid past mistakes but drift away from approaches the user has already validated, and may grow overly cautious.</description>
- <when_to_save>Any time the user corrects your approach ("no not that", "don't", "stop doing X") OR confirms a non-obvious approach worked ("yes exactly", "perfect, keep doing that", accepting an unusual choice without pushback). Corrections are easy to notice; confirmations are quieter — watch for them. In both cases, save what is applicable to future conversations, especially if surprising or not obvious from the code. Include *why* so you can judge edge cases later.</when_to_save>
- <how_to_use>Let these memories guide your behavior so that the user does not need to offer the same guidance twice.</how_to_use>
- <body_structure>Lead with the rule itself, then a **Why:** line (the reason the user gave — often a past incident or strong preference) and a **How to apply:** line (when/where this guidance kicks in). Knowing *why* lets you judge edge cases instead of blindly following the rule.</body_structure>
+ <description>Guidance the user has given you about how to approach work \
+— both what to avoid and what to keep doing. These are a very important type \
+of memory to read and write as they allow you to remain coherent and \
+responsive to the way you should approach work in the project. Record from \
+failure AND success: if you only save corrections, you will avoid past \
+mistakes but drift away from approaches the user has already validated, \
+and may grow overly cautious.</description>
+ <when_to_save>Any time the user corrects your approach ("no not that", \
+"don't", "stop doing X") OR confirms a non-obvious approach worked \
+("yes exactly", "perfect, keep doing that", accepting an unusual choice \
+without pushback). Corrections are easy to notice; confirmations are quieter \
+— watch for them. In both cases, save what is applicable to future \
+conversations, especially if surprising or not obvious from the code. \
+Include *why* so you can judge edge cases later.</when_to_save>
+ <how_to_use>Let these memories guide your behavior so that the user \
+does not need to offer the same guidance twice.</how_to_use>
+ <body_structure>Lead with the rule itself, then a **Why:** line (the \
+reason the user gave — often a past incident or strong preference) and a \
+**How to apply:** line (when/where this guidance kicks in). Knowing *why* \
+lets you judge edge cases instead of blindly following the rule.\
+</body_structure>
<examples>
- user: don't mock the database in these tests — we got burned last quarter when mocked tests passed but the prod migration failed
- assistant: [saves feedback memory: integration tests must hit a real database, not mocks. Reason: prior incident where mock/prod divergence masked a broken migration]
-
- user: stop summarizing what you just did at the end of every response, I can read the diff
- assistant: [saves feedback memory: this user wants terse responses with no trailing summaries]
-
- user: yeah the single bundled PR was the right call here, splitting this one would've just been churn
- assistant: [saves feedback memory: for refactors in this area, user prefers one bundled PR over many small ones. Confirmed after I chose this approach — a validated judgment call, not a correction]
+ user: don't mock the database in these tests — we got burned last \
+quarter when mocked tests passed but the prod migration failed
+ assistant: [saves feedback memory: integration tests must hit a real \
+database, not mocks. Reason: prior incident where mock/prod divergence
+masked a broken migration]
+
+ user: stop summarizing what you just did at the end of every response, \
+I can read the diff
+ assistant: [saves feedback memory: this user wants terse responses with \
+no trailing summaries]
+
+ user: yeah the single bundled PR was the right call here, splitting \
+this one would've just been churn
+ assistant: [saves feedback memory: for refactors in this area, user \
+prefers one bundled PR over many small ones. Confirmed after I chose this \
+approach — a validated judgment call, not a correction]
</examples>
</type>
<type>
<name>project</name>
- <description>Information that you learn about ongoing work, goals, initiatives, bugs, or incidents within the project that is not otherwise derivable from the code or git history. Project memories help you understand the broader context and motivation behind the work the user is doing within this working directory.</description>
- <when_to_save>When you learn who is doing what, why, or by when. These states change relatively quickly so try to keep your understanding of this up to date. Always convert relative dates in user messages to absolute dates when saving (e.g., "Thursday" → "2026-03-05"), so the memory remains interpretable after time passes.</when_to_save>
- <how_to_use>Use these memories to more fully understand the details and nuance behind the user's request and make better informed suggestions.</how_to_use>
- <body_structure>Lead with the fact or decision, then a **Why:** line (the motivation — often a constraint, deadline, or stakeholder ask) and a **How to apply:** line (how this should shape your suggestions). Project memories decay fast, so the why helps future-you judge whether the memory is still load-bearing.</body_structure>
+ <description>Information that you learn about ongoing work, goals, \
+initiatives, bugs, or incidents within the project that is not otherwise \
+derivable from the code or git history. Project memories help you understand \
+the broader context and motivation behind the work the user is doing within \
+this working directory.</description>
+ <when_to_save>When you learn who is doing what, why, or by when. These \
+states change relatively quickly so try to keep your understanding of this \
+up to date. Always convert relative dates in user messages to absolute dates \
+when saving (e.g., "Thursday" → "2026-03-05"), so the memory remains \
+interpretable after time passes.</when_to_save>
+ <how_to_use>Use these memories to more fully understand the details and \
+nuance behind the user's request and make better informed suggestions.\
+</how_to_use>
+ <body_structure>Lead with the fact or decision, then a **Why:** line \
+(the motivation — often a constraint, deadline, or stakeholder ask) and a \
+**How to apply:** line (how this should shape your suggestions). \
+Project memories decay fast, so the why helps future-you judge whether \
+the memory is still load-bearing.</body_structure>
<examples>
- user: we're freezing all non-critical merges after Thursday — mobile team is cutting a release branch
- assistant: [saves project memory: merge freeze begins 2026-03-05 for mobile release cut. Flag any non-critical PR work scheduled after that date]
-
- user: the reason we're ripping out the old auth middleware is that legal flagged it for storing session tokens in a way that doesn't meet the new compliance requirements
- assistant: [saves project memory: auth middleware rewrite is driven by legal/compliance requirements around session token storage, not tech-debt cleanup — scope decisions should favor compliance over ergonomics]
+ user: we're freezing all non-critical merges after Thursday — mobile team \
+is cutting a release branch
+ assistant: [saves project memory: merge freeze begins 2026-03-05 for
+mobile release cut. Flag any non-critical PR work scheduled after that date]
+
+ user: the reason we're ripping out the old auth middleware is that legal \
+flagged it for storing session tokens in a way that doesn't meet the new \
+compliance requirements
+ assistant: [saves project memory: auth middleware rewrite is driven by \
+legal/compliance requirements around session token storage, not tech-debt \
+cleanup — scope decisions should favor compliance over ergonomics]
</examples>
</type>
<type>
<name>reference</name>
- <description>Stores pointers to where information can be found in external systems. These memories allow you to remember where to look to find up-to-date information outside of the project directory.</description>
- <when_to_save>When you learn about resources in external systems and their purpose. For example, that bugs are tracked in a specific project in Linear or that feedback can be found in a specific Slack channel.</when_to_save>
- <how_to_use>When the user references an external system or information that may be in an external system.</how_to_use>
+ <description>Stores pointers to where information can be found in \
+external systems. These memories allow you to remember where to look to \
+find up-to-date information outside of the project directory.</description>
+ <when_to_save>When you learn about resources in external systems and \
+their purpose. For example, that bugs are tracked in a specific project in \
+Linear or that feedback can be found in a specific Slack channel.\
+</when_to_save>
+ <how_to_use>When the user references an external system or information \
+that may be in an external system.</how_to_use>
<examples>
- user: check the Linear project "INGEST" if you want context on these tickets, that's where we track all pipeline bugs
- assistant: [saves reference memory: pipeline bugs are tracked in Linear project "INGEST"]
-
- user: the Grafana board at grafana.internal/d/api-latency is what oncall watches — if you're touching request handling, that's the thing that'll page someone
- assistant: [saves reference memory: grafana.internal/d/api-latency is the oncall latency dashboard — check it when editing request-path code]
+ user: check the Linear project "INGEST" if you want context on these \
+tickets, that's where we track all pipeline bugs
+ assistant: [saves reference memory: pipeline bugs are tracked in \
+Linear project "INGEST"]
+
+ user: the Grafana board at grafana.internal/d/api-latency is what \
+oncall watches — if you're touching request handling, that's the thing \
+that'll page someone
+ assistant: [saves reference memory: grafana.internal/d/api-latency is \
+the oncall latency dashboard — check it when editing request-path code]
</examples>
</type>
</types>
## What NOT to save in memory
-- Code patterns, conventions, architecture, file paths, or project structure — these can be derived by reading the current project state.
-- Git history, recent changes, or who-changed-what — `git log` / `git blame` are authoritative.
-- Debugging solutions or fix recipes — the fix is in the code; the commit message has the context.
+- Code patterns, conventions, architecture, file paths, or project \
+structure — these can be derived by reading the current project state.
+- Git history, recent changes, or who-changed-what — `git log` / `git blame` \
+are authoritative.
+- Debugging solutions or fix recipes — the fix is in the code; the commit \
+message has the context.
- Anything already documented in CLAUDE.md files.
-- Ephemeral task details: in-progress work, temporary state, current conversation context.
+- Ephemeral task details: in-progress work, temporary state, current \
+conversation context.
-These exclusions apply even when the user explicitly asks you to save. If they ask you to save a PR list or activity summary, ask what was *surprising* or *non-obvious* about it — that is the part worth keeping.
+These exclusions apply even when the user explicitly asks you to save. \
+If they ask you to save a PR list or activity summary, \
+ask what was *surprising* or *non-obvious* about it — \
+that is the part worth keeping.
## How to save memories
Saving a memory is a two-step process:
-**Step 1** — write the memory to its own file (e.g., `user_role.md`, `feedback_testing.md`) using this frontmatter format:
+**Step 1** — write the memory to its own file (e.g., `user_role.md`, \
+`feedback_testing.md`) using this frontmatter format:
```markdown
---
name: {{memory name}}
-description: {{one-line description — used to decide relevance in future conversations, so be specific}}
+description: {{the retrieval trigger — one line stating the situation in \
+which future-you should stop and Read this file before acting. \
+See "Writing the description field".}}
type: {{user, feedback, project, reference}}
---
-{{memory content — for feedback/project types, structure as: rule/fact, then **Why:** and **How to apply:** lines}}
+{{memory content — for feedback/project types, structure as: rule/fact, \
+then **Why:** and **How to apply:** lines}}
```
-**Step 2** — add a pointer to that file in `MEMORY.md`. `MEMORY.md` is an index, not a memory — each entry should be one line, under ~150 characters: - [Title](file.md) — one-line hook. It has no frontmatter. Never write memory content directly into MEMORY.md.
+**Step 2** — add a pointer to that file in `MEMORY.md`. `MEMORY.md` is an \
+index, not a memory — each entry should be one line, under ~150 characters: \
+- [Title](file.md) — one-line hook. It has no frontmatter. \
+Never write memory content directly into MEMORY.md.
-- MEMORY.md is always loaded into your conversation context — lines after 200 will be truncated, so keep the index concise
-- Keep the name, description, and type fields in memory files up-to-date with the content
+- MEMORY.md is always loaded into your conversation context — lines after \
+200 will be truncated, so keep the index concise
+- Keep the name, description, and type fields in memory files up-to-date with \
+the content
- Organize memory semantically by topic, not chronologically
- Update or remove memories that turn out to be wrong or outdated
-- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one.
+- Do not write duplicate memories. First check if there is an existing memory \
+you can update before writing a new one.
+
+## Writing the `description` field
+
+The `description` is not a summary of the file — it is the *retrieval \
+trigger* that a future conversation sees in `MEMORY.md` and in your system \
+prompt *before the file is ever opened*. \
+Write it so that from that one line alone, future-you can decide whether to \
+stop and `Read` the file. A description that only names the topic (e.g. \
+"notes on PR review") fails: it says what the file is about, not *when* \
+it becomes load-bearing.
+
+State **the recall condition** — the situation that should make you open the \
+file, phrased as a trigger, not a label. Prefer the form: "When you are \
+about to <situation> and this file's content is not already in your context, \
+Read it first, then act."
+
+- Weak: `Guidelines for reviewing PRs`
+- Strong: `When you are about to review a PR in the xxx repo and this file \
+is not already in your context, you must Read it before acting`
+
+Keep it to one line, but spend that line on the *trigger*, not on restating \
+the title.
## When to access memories
- When memories seem relevant, or the user references prior-conversation work.
-- You MUST access memory when the user explicitly asks you to check, recall, or remember.
-- If the user says to ignore or not use memory: proceed as if MEMORY.md were empty. Do not apply remembered facts, cite, compare against, or mention memory content.
-- Memory records can become stale over time. Use memory as context for what was true at a given point in time. Before answering the user or building assumptions based solely on information in memory records, verify that the memory is still correct and up-to-date by reading the current state of the files or resources. If a recalled memory conflicts with current information, trust what you observe now — and update or remove the stale memory rather than acting on it.
+- You MUST access memory when the user explicitly asks you to check, recall, \
+or remember.
+- If the user says to ignore or not use memory: proceed as if MEMORY.md were \
+empty. Do not apply remembered facts, cite, compare against, or mention \
+memory content.
+- Memory records can become stale over time. Use memory as context for what \
+was true at a given point in time. Before answering the user or building \
+assumptions based solely on information in memory records, verify that the \
+memory is still correct and up-to-date by reading the current state of the \
+files or resources. If a recalled memory conflicts with current information, \
+trust what you observe now — and update or remove the stale memory rather \
+than acting on it.
## Before recommending from memory
-A memory that names a specific function, file, or flag is a claim that it existed *when the memory was written*. It may have been renamed, removed, or never merged. Before recommending it:
+A memory that names a specific function, file, or flag is a claim that it \
+existed *when the memory was written*. It may have been renamed, removed, \
+or never merged. Before recommending it:
- If the memory names a file path: check the file exists.
- If the memory names a function or flag: grep for it.
-- If the user is about to act on your recommendation (not just asking about history), verify first.
+- If the user is about to act on your recommendation (not just asking \
+about history), verify first.
"The memory says X exists" is not the same as "X exists now."
-A memory that summarizes repo state (activity logs, architecture snapshots) is frozen in time. If the user asks about *recent* or *current* state, prefer `git log` or reading the code over recalling the snapshot.
+A memory that summarizes repo state (activity logs, architecture snapshots) \
+is frozen in time. \
+If the user asks about *recent* or *current* state, prefer `git log` or \
+reading the code over recalling the snapshot.
## Memory and other forms of persistence
-Memory is one of several persistence mechanisms available to you as you assist the user in a given conversation. The distinction is often that memory can be recalled in future conversations and should not be used for persisting information that is only useful within the scope of the current conversation.
-- When to use or update a plan instead of memory: If you are about to start a non-trivial implementation task and would like to reach alignment with the user on your approach you should use a Plan rather than saving this information to memory. Similarly, if you already have a plan within the conversation and you have changed your approach persist that change by updating the plan rather than saving a memory.
-- When to use or update tasks instead of memory: When you need to break your work in current conversation into discrete steps or keep track of your progress use tasks instead of saving to memory. Tasks are great for persisting information about the work that needs to be done in the current conversation, but memory should be reserved for information that will be useful in future conversations.
+Memory is one of several persistence mechanisms available to you as you \
+assist the user in a given conversation. The distinction is often that memory \
+can be recalled in future conversations and should not be used for persisting \
+information that is only useful within the scope of the current conversation.
+- When to use or update a plan instead of memory: If you are about to start a \
+non-trivial implementation task and would like to reach alignment with the \
+user on your approach you should use a Plan rather than saving this \
+information to memory. Similarly, if you already have a plan within the \
+conversation and you have changed your approach persist that change by \
+updating the plan rather than saving a memory.
+- When to use or update tasks instead of memory: When you need to break your \
+work in current conversation into discrete steps or keep track of your \
+progress use tasks instead of saving to memory. \
+Tasks are great for persisting information about the work that needs to \
+be done in the current conversation, but memory should be reserved for \
+information that will be useful in future conversations.
## Searching past context
@@ -178,7 +328,8 @@ Grep with pattern="<search>" path="{memory_dir}" glob="*.md"</search>
# or Bash command:
grep -rn "<search term>" {memory_dir} --include="*.md"
```
-Use narrow search terms (error messages, file paths, function names) rather than broad keywords.
+Use narrow search terms (error messages, file paths, function names) rather \
+than broad keywords.
""" # noqa:
DEFAULT_RETRIEVAL_INSTRUCTIONS = (
diff --git a/src/agentscope/tool/_task/_create_task.py b/src/agentscope/tool/_task/_create_task.py
index 2dc165e94..a6a772968 100644
--- a/src/agentscope/tool/_task/_create_task.py
+++ b/src/agentscope/tool/_task/_create_task.py
@@ -55,13 +55,13 @@ tasks discovered during implementation
## When NOT to Use This Tool
Skip using this tool when:
-- There is only a single, straightforward task
+- There is only **one single, straightforward** task
- The task is trivial and tracking it provides no organizational benefit
- The task can be completed in less than 3 trivial steps
- The task is purely conversational or informational
-NOTE that you should not use this tool if there is only one trivial task to \
-do. In this case you are better off just doing the task directly.
+NOTE that you should **NOT** use this tool if there is only one trivial task \
+to do. In this case you are better off just doing the task directly.
## Task Fields
diff --git a/src/agentscope/workspace/_daytona/_daytona_workspace.py b/src/agentscope/workspace/_daytona/_daytona_workspace.py
index 3c08fccfc..808063ab8 100644
--- a/src/agentscope/workspace/_daytona/_daytona_workspace.py
+++ b/src/agentscope/workspace/_daytona/_daytona_workspace.py
@@ -50,7 +50,7 @@ from typing import Any
from ..._logging import logger
from ...mcp import MCPClient
from .._sandboxed_base import SandboxedWorkspaceBase
-from .._utils import _GATEWAY_BASE_REQUIREMENTS
+from .._utils import _GATEWAY_BASE_REQUIREMENTS, DEFAULT_WORKSPACE_INSTRUCTIONS
from ._constants import (
DEFAULT_GATEWAY_PORT,
DEFAULT_TIMEOUT,
@@ -59,24 +59,6 @@ from ._constants import (
)
from ._daytona_backend import DaytonaBackend
-_DEFAULT_INSTRUCTIONS = """<workspace>
-You have a Daytona-based sandbox workspace. All tool calls execute
-inside the sandbox at ``{workdir}``.
-
-Layout:
-
-```
-{workdir}
-├── data/ # offloaded multimodal files
-├── skills/ # reusable skills
-└── sessions/ # session context and tool results
-```
-
-Use the MCP-provided tools to interact with the sandbox filesystem
-and processes.
-</workspace>"""
-
-
# ── the workspace ──────────────────────────────────────────────────
@@ -106,7 +88,7 @@ class DaytonaWorkspace(SandboxedWorkspaceBase):
env: dict[str, str] | None = None,
sandbox_metadata: dict[str, str] | None = None,
extra_pip: list[str] | None = None,
- instructions: str = _DEFAULT_INSTRUCTIONS,
+ instructions: str = DEFAULT_WORKSPACE_INSTRUCTIONS,
default_mcps: list[MCPClient] | None = None,
skill_paths: list[str] | None = None,
os_user: str | None = None,
@@ -143,7 +125,7 @@ class DaytonaWorkspace(SandboxedWorkspaceBase):
extra_pip (`list[str] | None`, optional):
Extra Python packages installed into the gateway venv
during bootstrap.
- instructions (`str`, defaults to `_DEFAULT_INSTRUCTIONS`):
+ instructions (`str`, defaults to `DEFAULT_WORKSPACE_INSTRUCTIONS`):
System-prompt fragment template (supports ``{workdir}``).
default_mcps (`list[MCPClient] | None`, optional):
MCPs registered on first init when no persisted
@@ -238,8 +220,10 @@ class DaytonaWorkspace(SandboxedWorkspaceBase):
SDK-reported sandbox workdir. Before initialization, a readable
placeholder is used because Daytona paths are not known yet.
"""
- workdir = self.workdir or "<sandbox workdir>"
- return self.instructions.format(workdir=workdir)
+ return self.instructions.format(
+ backend="Daytona-based",
+ workdir=self.workdir or "<unknown>",
+ )
# ── internals: Daytona client / sandbox attach / create ─────
diff --git a/src/agentscope/workspace/_docker/_docker_workspace.py b/src/agentscope/workspace/_docker/_docker_workspace.py
index e28efa63d..016b32d2a 100644
--- a/src/agentscope/workspace/_docker/_docker_workspace.py
+++ b/src/agentscope/workspace/_docker/_docker_workspace.py
@@ -23,6 +23,7 @@ import sys
import tarfile
from typing import Any
+from .._utils import DEFAULT_WORKSPACE_INSTRUCTIONS
from ..._logging import logger
from ...mcp import MCPClient
from .._sandboxed_base import SandboxedWorkspaceBase
@@ -35,20 +36,6 @@ from ._make_dockerfile import (
prepare_build_context,
)
-_DEFAULT_INSTRUCTIONS = """<workspace>
-You have a Docker-based workspace. All tool calls execute **inside the
-container** at ``{workdir}``.
-
-Layout:
-
-```
-{workdir}
-├── data/ # offloaded multimodal files
-├── skills/ # reusable skills
-└── sessions/ # session context and tool results
-```
-</workspace>"""
-
# ── the workspace ──────────────────────────────────────────────────
@@ -72,7 +59,7 @@ class DockerWorkspace(SandboxedWorkspaceBase):
extra_pip: list[str] | None = None,
gateway_port: int = DEFAULT_GATEWAY_PORT,
env: dict[str, str] | None = None,
- instructions: str = _DEFAULT_INSTRUCTIONS,
+ instructions: str = DEFAULT_WORKSPACE_INSTRUCTIONS,
default_mcps: list[MCPClient] | None = None,
skill_paths: list[str] | None = None,
**kwargs: Any,
@@ -102,7 +89,7 @@ class DockerWorkspace(SandboxedWorkspaceBase):
(no host port mapping).
env (`dict[str, str] | None`, optional):
Environment variables to set inside the container.
- instructions (`str`, defaults to `_DEFAULT_INSTRUCTIONS`):
+ instructions (`str`, defaults to `DEFAULT_WORKSPACE_INSTRUCTIONS`):
System-prompt fragment template; supports ``{workdir}``.
default_mcps (`list[MCPClient] | None`, optional):
MCPs registered on first init when no persisted
@@ -133,7 +120,10 @@ class DockerWorkspace(SandboxedWorkspaceBase):
self.extra_pip: list[str] = list(extra_pip or [])
self.gateway_port = gateway_port
self.env: dict[str, str] = dict(env or {})
- self.instructions = instructions
+ self.instructions = instructions.format(
+ backend="Docker-based",
+ workdir=self.workdir,
+ )
# ── runtime state (Docker-only) ─────────────────────────
self._client: Any = None # aiodocker.Docker
@@ -205,7 +195,7 @@ class DockerWorkspace(SandboxedWorkspaceBase):
async def get_instructions(self) -> str:
"""Return the system-prompt fragment, formatted with the
container-side ``{workdir}``."""
- return self.instructions.format(workdir=CONTAINER_WORKDIR)
+ return self.instructions
# ── internals: image build ──────────────────────────────────
diff --git a/src/agentscope/workspace/_e2b/_e2b_workspace.py b/src/agentscope/workspace/_e2b/_e2b_workspace.py
index f08dcc6e1..40b21007b 100644
--- a/src/agentscope/workspace/_e2b/_e2b_workspace.py
+++ b/src/agentscope/workspace/_e2b/_e2b_workspace.py
@@ -44,7 +44,7 @@ from typing import Any
from ..._logging import logger
from ...mcp import MCPClient
from .._sandboxed_base import SandboxedWorkspaceBase
-from .._utils import _GATEWAY_BASE_REQUIREMENTS
+from .._utils import _GATEWAY_BASE_REQUIREMENTS, DEFAULT_WORKSPACE_INSTRUCTIONS
from ._constants import (
DEFAULT_GATEWAY_PORT,
DEFAULT_TEMPLATE,
@@ -55,20 +55,6 @@ from ._constants import (
)
from ._e2b_backend import E2BBackend
-_DEFAULT_INSTRUCTIONS = """<workspace>
-You have an E2B-based cloud workspace. All tool calls execute **inside
-the sandbox** at ``{workdir}``.
-
-Layout:
-
-```
-{workdir}
-├── data/ # offloaded multimodal files
-├── skills/ # reusable skills
-└── sessions/ # session context and tool results
-```
-</workspace>"""
-
# ── the workspace ──────────────────────────────────────────────────
@@ -98,7 +84,7 @@ class E2BWorkspace(SandboxedWorkspaceBase):
env: dict[str, str] | None = None,
sandbox_metadata: dict[str, str] | None = None,
extra_pip: list[str] | None = None,
- instructions: str = _DEFAULT_INSTRUCTIONS,
+ instructions: str = DEFAULT_WORKSPACE_INSTRUCTIONS,
default_mcps: list[MCPClient] | None = None,
skill_paths: list[str] | None = None,
) -> None:
@@ -128,7 +114,7 @@ class E2BWorkspace(SandboxedWorkspaceBase):
extra_pip (`list[str] | None`, optional):
Extra Python packages installed into the gateway venv
during bootstrap.
- instructions (`str`, defaults to `_DEFAULT_INSTRUCTIONS`):
+ instructions (`str`, defaults to `DEFAULT_WORKSPACE_INSTRUCTIONS`):
System-prompt fragment template (supports ``{workdir}``).
default_mcps (`list[MCPClient] | None`, optional):
MCPs registered on first init when no persisted
@@ -152,7 +138,10 @@ class E2BWorkspace(SandboxedWorkspaceBase):
self.env: dict[str, str] = dict(env or {})
self.sandbox_metadata: dict[str, str] = dict(sandbox_metadata or {})
self.extra_pip: list[str] = list(extra_pip or [])
- self.instructions = instructions
+ self.instructions = instructions.format(
+ backend="E2B-based",
+ workdir=self.workdir,
+ )
# ── runtime state (E2B-only) ────────────────────────────
self._sandbox: Any = None # e2b.AsyncSandbox
diff --git a/src/agentscope/workspace/_k8s/_k8s_workspace.py b/src/agentscope/workspace/_k8s/_k8s_workspace.py
index 61054b4ac..2a99b3e03 100644
--- a/src/agentscope/workspace/_k8s/_k8s_workspace.py
+++ b/src/agentscope/workspace/_k8s/_k8s_workspace.py
@@ -33,7 +33,7 @@ from typing import Any
from ..._logging import logger
from ...mcp import MCPClient
from .._sandboxed_base import SandboxedWorkspaceBase
-from .._utils import _GATEWAY_BASE_REQUIREMENTS
+from .._utils import _GATEWAY_BASE_REQUIREMENTS, DEFAULT_WORKSPACE_INSTRUCTIONS
from ._k8s_backend import K8sBackend
from ._constants import (
DEFAULT_GATEWAY_PORT,
@@ -44,20 +44,6 @@ from ._constants import (
_k8s_safe_name,
)
-_DEFAULT_INSTRUCTIONS = """<workspace>
-You have a Kubernetes-based workspace. All tool calls execute **inside
-the Pod** at ``{workdir}``.
-
-Layout:
-
-```
-{workdir}
-├── data/ # offloaded multimodal files
-├── skills/ # reusable skills
-└── sessions/ # session context and tool results
-```
-</workspace>"""
-
# ── the workspace ──────────────────────────────────────────────────
@@ -95,7 +81,7 @@ class K8sWorkspace(SandboxedWorkspaceBase):
delete_pvc_on_close: bool = False,
# ── Environment ──
env: dict[str, str] | None = None,
- instructions: str = _DEFAULT_INSTRUCTIONS,
+ instructions: str = DEFAULT_WORKSPACE_INSTRUCTIONS,
# ── Seed ──
default_mcps: list[MCPClient] | None = None,
skill_paths: list[str] | None = None,
@@ -169,7 +155,10 @@ class K8sWorkspace(SandboxedWorkspaceBase):
self._storage_size = storage_size
self._delete_pvc_on_close = delete_pvc_on_close
self.env: dict[str, str] = dict(env or {})
- self.instructions = instructions
+ self.instructions = instructions.format(
+ backend="Kubernetes-based",
+ workdir=self.workdir,
+ )
# ── runtime state (K8s-only) ────────────────────────────
self._api_client: Any = None
@@ -248,7 +237,7 @@ class K8sWorkspace(SandboxedWorkspaceBase):
async def get_instructions(self) -> str:
"""Return the system-prompt fragment for this workspace."""
- return self.instructions.format(workdir=POD_WORKDIR)
+ return self.instructions
# ── internals: K8s resource management ─────────────────────
diff --git a/src/agentscope/workspace/_local_workspace.py b/src/agentscope/workspace/_local_workspace.py
index 7db64c20b..29424eb03 100644
--- a/src/agentscope/workspace/_local_workspace.py
+++ b/src/agentscope/workspace/_local_workspace.py
@@ -11,6 +11,7 @@ from typing import TypedDict
import frontmatter
+from ._utils import DEFAULT_WORKSPACE_INSTRUCTIONS
from .._logging import logger
from ..mcp import MCPClient
from ..skill import Skill
@@ -54,45 +55,6 @@ def _sanitize_dir_name(name: str) -> str:
return re.sub(r"[^\w一-鿿-]", "_", name)
-_DEFAULT_WORKSPACE_INSTRUCTIONS = """<workspace>
-You have access to a local workspace at {workdir} with the following structure:
-
-```
-{workdir}
-├── data/ # offloaded multimodal files (images, etc.)
-├── skills/ # reusable skills, each in its own subdirectory
-└── sessions/ # session context and tool results
-```
-
-This workspace is your personal working environment for completing various tasks.
-You are responsible for keeping it clean, structured, and easy to navigate over time.
-
-### Project Directory
-- Create a dedicated subdirectory for each task or project under the workspace root.
-- Name the directory concisely and descriptively, e.g. `20240315_web-scraper`, so it remains identifiable long after creation.
-- Always create a `README.md` at the project root documenting:
- - What the project is about
- - When it was created
- - Key decisions or context that would help you resume work later
- - The changes you have made (and when)
-
-### Version Control
-- It is recommended to initialize a `git` repository in each project directory
- to track changes and allow rollbacks.
-- Always create a `.gitignore` before the first commit to exclude unwanted files
- (e.g. virtual environments, cache, secrets).
-
-### Python Environment
-- If a project requires Python, use `uv` to create an isolated virtual environment
- inside the project directory:
- ```shell
- uv venv && uv pip install ...
- ```
-- Never install packages into a shared or global environment — each project must
- manage its own dependencies to avoid conflicts.
-</workspace>""" # noqa: E501
-
-
class LocalWorkspace(WorkspaceBase):
"""Local-directory workspace.
@@ -112,7 +74,7 @@ class LocalWorkspace(WorkspaceBase):
workspace_id: str | None = None,
default_mcps: list[MCPClient] | None = None,
skill_paths: list[str] | None = None,
- instructions: str = _DEFAULT_WORKSPACE_INSTRUCTIONS,
+ instructions: str = DEFAULT_WORKSPACE_INSTRUCTIONS,
) -> None:
"""Construct a :class:`LocalWorkspace`.
@@ -140,7 +102,10 @@ class LocalWorkspace(WorkspaceBase):
# ── serializable config ─────────────────────────────────
self.workdir = os.path.abspath(workdir)
- self.instructions = instructions.format(workdir=self.workdir)
+ self.instructions = instructions.format(
+ backend="local",
+ workdir=self.workdir,
+ )
# ── seed-only ───────────────────────────────────────────
self.default_mcps: list[MCPClient] = list(default_mcps or [])
diff --git a/src/agentscope/workspace/_opensandbox/_opensandbox_workspace.py b/src/agentscope/workspace/_opensandbox/_opensandbox_workspace.py
index 359c4802e..346a118b8 100644
--- a/src/agentscope/workspace/_opensandbox/_opensandbox_workspace.py
+++ b/src/agentscope/workspace/_opensandbox/_opensandbox_workspace.py
@@ -11,7 +11,7 @@ from typing import TYPE_CHECKING, Literal
from ..._logging import logger
from ...mcp import MCPClient
from .._sandboxed_base import SandboxedWorkspaceBase
-from .._utils import _GATEWAY_BASE_REQUIREMENTS
+from .._utils import _GATEWAY_BASE_REQUIREMENTS, DEFAULT_WORKSPACE_INSTRUCTIONS
from ._constants import (
DEFAULT_GATEWAY_PORT,
DEFAULT_IMAGE,
@@ -33,21 +33,6 @@ if TYPE_CHECKING:
)
-_DEFAULT_INSTRUCTIONS = """<workspace>
-You have an OpenSandbox-based workspace. All tool calls execute **inside
-the sandbox** at ``{workdir}``.
-
-Layout:
-
-```
-{workdir}
-├── data/ # offloaded multimodal files
-├── skills/ # reusable skills
-└── sessions/ # session context and tool results
-```
-</workspace>"""
-
-
class OpenSandboxWorkspace(SandboxedWorkspaceBase):
"""Workspace backed by an OpenSandbox sandbox.
@@ -78,7 +63,7 @@ class OpenSandboxWorkspace(SandboxedWorkspaceBase):
entrypoint: list[str] | None = None,
network_policy: NetworkPolicy | None = None,
extra_pip: list[str] | None = None,
- instructions: str = _DEFAULT_INSTRUCTIONS,
+ instructions: str = DEFAULT_WORKSPACE_INSTRUCTIONS,
default_mcps: list[MCPClient] | None = None,
skill_paths: list[str] | None = None,
) -> None:
@@ -121,8 +106,9 @@ class OpenSandboxWorkspace(SandboxedWorkspaceBase):
extra_pip (`list[str] | None`, optional):
Extra Python packages installed into the gateway venv
during bootstrap.
- instructions (`str`, defaults to `_DEFAULT_INSTRUCTIONS`):
- System-prompt fragment template (supports ``{workdir}``).
+ instructions (`str`, defaults to `DEFAULT_WORKSPACE_INSTRUCTIONS`):
+ Instructions that will be injected into the system prompt,
+ which should receive placeholders "{workdir}".
default_mcps (`list[MCPClient] | None`, optional):
MCPs registered on first init when no persisted
``.mcp`` exists.
@@ -207,7 +193,10 @@ class OpenSandboxWorkspace(SandboxedWorkspaceBase):
the sandbox-side path (``/workspace``). The agent always sees
sandbox-internal paths.
"""
- return self.instructions.format(workdir=SANDBOX_WORKDIR)
+ return self.instructions.format(
+ backend="OpenSandbox",
+ workdir=self.workdir,
+ )
def _connection_config(self) -> ConnectionConfig:
"""Build OpenSandbox connection config on demand."""
diff --git a/src/agentscope/workspace/_utils.py b/src/agentscope/workspace/_utils.py
index 848ea37a7..0686feb4a 100644
--- a/src/agentscope/workspace/_utils.py
+++ b/src/agentscope/workspace/_utils.py
@@ -14,6 +14,69 @@ import importlib.resources as _res
# ── shared constants ───────────────────────────────────────────────
+#: Standard prompt injected to the system prompt
+DEFAULT_WORKSPACE_INSTRUCTIONS = """<workspace>You have access to a {backend} \
+workspace at {workdir} with the following structure:
+
+```
+{workdir}
+├── data/ # offloaded multimodal files (images, etc.) — system-managed
+├── skills/ # reusable skills, each in its own subdirectory
+└── sessions/ # offloaded session context and tool results — system-managed
+```
+
+This workspace is your personal working environment. You are responsible for \
+keeping it clean, structured, and easy to navigate over time.
+
+### Project Directory
+- Create a dedicated subdirectory for each task or project under the \
+workspace root.
+- Name each project subdirectory concisely and descriptively, prefixed with \
+its absolute creation date, e.g. `20240315_web-scraper`, so it stays \
+identifiable long after creation.
+- Always create a `README.md` at the project root documenting:
+ - What the project is about
+ - Its absolute creation date
+ - Key decisions or context that would help you resume work later
+
+### Working Across Sessions
+- The same project may be worked on from more than one session at a time. \
+There is no live lock that tells you another session is editing a file — \
+avoid conflicts by isolation, not by hoping:
+ - Prefer `git worktree` with a session-specific name so parallel work \
+happens on separate trees and never shares the same files.
+ - Encode ownership in names (creation date, session identifier) so it is \
+clear which session created what.
+- Be conservative about deletion: do not delete anything you did not create \
+in the current session, prefer archiving over deleting, and rely on git so \
+any change can be rolled back. Confirm before destructive cleanup.
+
+### Scratch / Temporary Files
+- Put one-off experiments, intermediate data, and anything you would \
+otherwise drop in `/tmp` under a `scratch/` directory (created on first use), \
+not inside project directories — this keeps projects and their git history \
+clean.
+- Treat `scratch/` as disposable: exclude it from git, and assume nothing in \
+it is guaranteed to persist. Nothing clears it automatically (it lives inside \
+your persistent workspace, not the OS temp dir), so delete your own scratch \
+files when you are done with them.
+
+### Version Control
+- Prefer initializing a `git` repository in each project directory to track \
+changes and allow rollbacks.
+- If you use git, create a `.gitignore` before the first commit to exclude \
+unwanted files (e.g. virtual environments, cache, `scratch/`, secrets).
+- Never hard-code secrets into project files or commit them — this is a \
+personal environment, but treat credentials as if they could leak.
+
+### Python Environment
+- `uv` is recommended for managing and isolating Python environments per \
+project:
+```shell
+uv venv && uv pip install ...
+- Never install packages into a shared or global environment — each project \
+must manage its own dependencies to avoid conflicts.</workspace>"""
+
#: Standard workspace-relative directory for offloaded multimodal data.
DEFAULT_DATA_DIR = "data"
diff --git a/tests/workspace_local_test.py b/tests/workspace_local_test.py
index d726a6335..b9961ec51 100644
--- a/tests/workspace_local_test.py
+++ b/tests/workspace_local_test.py
@@ -855,7 +855,7 @@ class TestLocalWorkspaceWithAgent(IsolatedAsyncioTestCase):
"""
with tempfile.TemporaryDirectory() as workdir:
session_id = "test_session"
- model = MockModel(stream=False)
+ model = MockModel(stream=False, context_size=100000)
agent = Agent(
name="Friday",
system_prompt="You're a helpful assistant named Friday.",