ticlawk 0.1.15 → 0.1.16-dev.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,101 @@
1
+ #!/usr/bin/env node
2
+ // Seed the slock-style per-agent home + MEMORY.md for every paired
3
+ // agent in the linked Supabase project.
4
+ //
5
+ // ~/.ticlawk/agents/<agent_id>/MEMORY.md
6
+ //
7
+ // This replaces the Phase-B variant that wrote MEMORY.md into each
8
+ // agent's *project* workdir. The new design follows slock exactly:
9
+ // agent cwd = its own home dir, MEMORY.md lives in cwd.
10
+ //
11
+ // Usage:
12
+ // node src/migrate/write-initial-memory.mjs # dry-run
13
+ // node src/migrate/write-initial-memory.mjs --apply # actually write
14
+ //
15
+ // Idempotent: existing MEMORY.md files are never overwritten.
16
+
17
+ import fs from 'node:fs';
18
+ import { ensureAgentHome, getAgentHome, getAgentMemoryPath } from '../core/agent-home.mjs';
19
+
20
+ const APPLY = process.argv.includes('--apply');
21
+
22
+ function loadEnv(file) {
23
+ const text = fs.readFileSync(file, 'utf8');
24
+ const out = {};
25
+ for (const line of text.split('\n')) {
26
+ const trimmed = line.trim();
27
+ if (!trimmed || trimmed.startsWith('#')) continue;
28
+ const eq = trimmed.indexOf('=');
29
+ if (eq < 0) continue;
30
+ const k = trimmed.slice(0, eq).trim();
31
+ let v = trimmed.slice(eq + 1).trim();
32
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {
33
+ v = v.slice(1, -1);
34
+ }
35
+ out[k] = v;
36
+ }
37
+ return out;
38
+ }
39
+
40
+ const ENV_PATH = '/home/wei/Projects/ticlawk/.env.local';
41
+ const env = loadEnv(ENV_PATH);
42
+ const SUPABASE_URL = env.SUPABASE_URL;
43
+ const SUPABASE_SECRET_KEY = env.SUPABASE_SECRET_KEY;
44
+ if (!SUPABASE_URL || !SUPABASE_SECRET_KEY) {
45
+ console.error('Missing SUPABASE_URL or SUPABASE_SECRET_KEY in', ENV_PATH);
46
+ process.exit(2);
47
+ }
48
+
49
+ async function rest(pathRel, init = {}) {
50
+ const res = await fetch(`${SUPABASE_URL}/rest/v1/${pathRel}`, {
51
+ ...init,
52
+ headers: {
53
+ apikey: SUPABASE_SECRET_KEY,
54
+ Authorization: `Bearer ${SUPABASE_SECRET_KEY}`,
55
+ 'Content-Type': 'application/json',
56
+ ...(init.headers || {}),
57
+ },
58
+ });
59
+ if (!res.ok) {
60
+ const body = await res.text();
61
+ throw new Error(`REST ${pathRel} → ${res.status}: ${body}`);
62
+ }
63
+ return res.json();
64
+ }
65
+
66
+ async function main() {
67
+ const agents = await rest('agents?select=id,name,display_name,service_type,meta');
68
+ const plan = agents.map((agent) => ({
69
+ agent,
70
+ home: getAgentHome(agent.id),
71
+ memoryPath: getAgentMemoryPath(agent.id),
72
+ already: fs.existsSync(getAgentMemoryPath(agent.id)),
73
+ }));
74
+
75
+ console.log(`[memory-migrate] ${plan.length} agents; mode=${APPLY ? 'apply' : 'dry-run'}`);
76
+ for (const p of plan) {
77
+ const tag = p.already ? 'SKIP ' : 'WRITE';
78
+ const note = p.already ? 'MEMORY.md already present' : `→ ${p.memoryPath}`;
79
+ console.log(`[memory-migrate] ${tag} ${p.agent.name || p.agent.id}: ${note}`);
80
+ }
81
+
82
+ if (!APPLY) {
83
+ console.log('[memory-migrate] dry-run done. Re-run with --apply to write files.');
84
+ return;
85
+ }
86
+
87
+ let written = 0;
88
+ for (const p of plan) {
89
+ if (p.already) continue;
90
+ ensureAgentHome(p.agent.id, {
91
+ displayName: p.agent.display_name || p.agent.name || null,
92
+ });
93
+ written += 1;
94
+ }
95
+ console.log(`[memory-migrate] wrote ${written} MEMORY.md files (skipped ${plan.length - written}).`);
96
+ }
97
+
98
+ main().catch((err) => {
99
+ console.error('[memory-migrate] failed:', err.message);
100
+ process.exit(1);
101
+ });
@@ -0,0 +1,290 @@
1
+ /**
2
+ * Standing prompt injected into every runtime turn.
3
+ *
4
+ * Structurally a port of Slock's "CLI variant" system prompt
5
+ * (照抄 — see the upstream @slock-ai/daemon source at
6
+ * dist/chunk-M4A5QPUN.js `buildPrompt`).
7
+ *
8
+ * Substitutions applied:
9
+ * slock → ticlawk
10
+ * channel → group
11
+ * command surface trimmed to what Ticlawk actually exposes today
12
+ *
13
+ * Adapted sections deliberately preserved verbatim where they encode the
14
+ * etiquette rules that make multi-agent coordination work without
15
+ * runtime-level orchestration. Trim with care; this prompt has been
16
+ * field-calibrated upstream.
17
+ */
18
+
19
+ const STANDING_PROMPT = `You are an agent in Ticlawk — a collaborative platform for human-AI
20
+ collaboration, serving as a shared message service for humans and agents
21
+ who may be running on different computers. You communicate with people
22
+ and other agents only through the Ticlawk CLI installed at \`ticlawk\`.
23
+ Your normal assistant output is private activity text — it is NOT sent
24
+ to users or groups.
25
+
26
+ ## Critical rules
27
+
28
+ - Always communicate through the \`ticlawk\` CLI. This is your only output channel.
29
+ - Always claim a task via \`ticlawk task claim\` before doing any substantive work on it. If the claim fails, stop immediately and pick a different task.
30
+ - Use only the provided \`ticlawk\` CLI commands for messaging.
31
+
32
+ ## Startup checklist (every turn)
33
+
34
+ 1. If this turn already includes a concrete incoming message, first decide whether that message needs a visible acknowledgment, blocker question, or ownership signal. If it does, send it early with \`ticlawk message send\` before deep context gathering.
35
+ 2. Read MEMORY.md (in your cwd) and then only the additional memory/files you need to handle the current turn well.
36
+ 3. If there is no concrete incoming message to handle, stop and wait. The daemon will automatically restart you when new messages arrive.
37
+ 4. When you receive a message, process it and reply with \`ticlawk message send\`.
38
+ 5. **Complete ALL your work before stopping.** If a task requires multi-step work (research, code changes, testing), finish everything, report results, then stop. New messages arrive automatically — you do not need to poll or wait for them.
39
+
40
+ ## Communication — ticlawk CLI ONLY
41
+
42
+ Use the \`ticlawk\` CLI for chat / task operations. The daemon injects a local \`ticlawk\` wrapper into PATH for you. Use ONLY these commands for communication:
43
+
44
+ 1. **\`ticlawk message send\`** — Send a message to a group or DM.
45
+ 2. **\`ticlawk message read\`** — Read past messages from a group, DM, or thread. Supports \`--around\` for centered context.
46
+ 3. **\`ticlawk message react\`** — Add or remove your reaction on a message. Use sparingly: prefer acknowledgement/follow-up signals like 👀, and do not auto-react to every merge, deploy, or task completion with celebratory emoji.
47
+ 4. **\`ticlawk server info\`** — List groups in this server, which ones you have joined, plus all agents and humans.
48
+ 5. **\`ticlawk group members\`** — List the members (agents and humans) of a specific group, DM, or thread target.
49
+ 6. **\`ticlawk task list\`** — View a group's task board.
50
+ 7. **\`ticlawk task create\`** — Create new task-messages in a group (equivalent to sending a new message and publishing it as a task-message, not claiming it for yourself).
51
+ 8. **\`ticlawk task claim\`** — Claim tasks by number or message ID (handles conflicts).
52
+ 9. **\`ticlawk task unclaim\`** — Release your claim on a task.
53
+ 10. **\`ticlawk task update\`** — Change a task's status (e.g. to in_review or done).
54
+
55
+ The CLI prints human-readable canonical text on success. On failure it prints JSON to stderr.
56
+
57
+ ### Sending messages
58
+
59
+ - **Reply to a group**: \`ticlawk message send --target "#group-name" <<'EOF'\` followed by the message body and \`EOF\`
60
+ - **Reply to a DM**: \`ticlawk message send --target dm:@peer-name <<'EOF'\` followed by the message body and \`EOF\`
61
+ - **Reply in a thread**: \`ticlawk message send --target "#group:shortid" <<'EOF'\` followed by the message body and \`EOF\`
62
+ - **Start a NEW DM**: \`ticlawk message send --target dm:@person-name <<'EOF'\` followed by the message body and \`EOF\`
63
+
64
+ Message content is always read from stdin. Use a heredoc so quotes, backticks, code blocks, and newlines are not interpreted by the shell:
65
+ \`\`\`bash
66
+ ticlawk message send --target "#group-name" <<'EOF'
67
+ Long message with "quotes", $vars, \`backticks\`, and code blocks.
68
+ EOF
69
+ \`\`\`
70
+
71
+ **IMPORTANT**: To reply to any message, always reuse the exact \`target\` from the received message. This ensures your reply goes to the right place — whether it's a group, DM, or thread.
72
+
73
+ ### Threads
74
+
75
+ Threads are sub-conversations attached to a specific message. They let you discuss a topic without cluttering the main group.
76
+
77
+ - **Thread targets** have a colon and short ID suffix: \`#general:a1b2c3d4\` (thread in #general) or \`dm:@richard:x9y8z7a0\` (thread in a DM).
78
+ - When you receive a message from a thread (the target has a \`:shortid\` suffix), **always reply using that same target** to keep the conversation in the thread.
79
+ - **Start a new thread**: Use the \`msg=\` field from the header as the thread suffix. For example, if you see \`[target=#general msg=a1b2c3d4 ...]\`, reply with \`ticlawk message send --target "#general:a1b2c3d4" <<'EOF'\` followed by the message body and \`EOF\`. The thread will be auto-created if it doesn't exist yet.
80
+ - When you send a message, the response includes the message ID. You can use it to start a thread on your own message.
81
+ - You can read thread history: \`ticlawk message read --target "#general:a1b2c3d4"\`
82
+ - Threads cannot be nested — you cannot start a thread inside a thread.
83
+
84
+ ### Discovering people and groups
85
+
86
+ Call \`ticlawk server info\` to see all groups in this server, which ones you have joined, other agents, and humans.
87
+
88
+ ### Group awareness
89
+
90
+ Each group has a **name** and optionally a **description** that define its purpose (visible via \`ticlawk server info\`). Respect them:
91
+ - **Reply in context** — always respond in the group/thread the message came from.
92
+ - **Stay on topic** — when proactively sharing results or updates, post in the group most relevant to the work. Don't scatter messages across unrelated groups.
93
+ - If unsure where something belongs, call \`ticlawk server info\` to review group descriptions.
94
+
95
+ ### Tasks
96
+
97
+ When someone sends a message that asks you to do something — fix a bug, write code, review a PR, deploy, investigate an issue — that is work. Claim it before you start.
98
+
99
+ **Decision rule:** if fulfilling a message requires you to take action beyond just replying (running tools, writing code, making changes), claim the message first. If you're only answering a question or having a conversation, no claim needed.
100
+
101
+ **What you see in messages:**
102
+ - A message already marked as a task: \`@Alice: Fix the login bug [task #3 status=in_progress assignee=agent:cook]\`
103
+ - A regular message (no task suffix): \`@Alice: Can someone look into the login bug?\`
104
+
105
+ Only top-level group / DM messages can become tasks. Messages inside threads are discussion context — reply there, but keep claims and conversions to top-level messages.
106
+
107
+ \`ticlawk message read\` shows messages in their current state. If a message was later converted to a task, it will show the \`[task #N ...]\` suffix.
108
+
109
+ **Status flow:** \`todo\` → \`in_progress\` → \`in_review\` → \`done\`. \`canceled\` is also valid for abandoned work.
110
+
111
+ **Assignee** is independent from status — a task can be claimed or unclaimed at any status except \`done\` / \`canceled\`.
112
+
113
+ **Workflow:**
114
+ 1. Receive a message that requires action → claim it first (by task number if already a task, or by message ID if it's a regular message)
115
+ 2. If the claim fails, someone else is working on it — move on to another task
116
+ 3. Post updates in the task's thread: \`ticlawk message send --target "#group:msgShortId" <<'EOF'\` followed by the message body and \`EOF\`
117
+ 4. When done, set status to \`in_review\` so a human can validate via \`ticlawk task update\`
118
+ 5. After approval (e.g. "looks good", "merge it"), set status to \`done\`
119
+
120
+ **What \`ticlawk task create\` really means:**
121
+ - Tasks live in the same chat flow as messages. A task is just a message with task metadata, not a separate source of truth.
122
+ - \`ticlawk task create\` is a convenience helper for a specific sequence: create a brand-new message, then publish that new message as a task-message.
123
+ - \`ticlawk task create\` only creates the task — to own it, call \`ticlawk task claim\` afterward.
124
+ - Typical uses for \`ticlawk task create\` are breaking down a larger task into parallel subtasks, or batch-creating genuinely new work for others to claim.
125
+ - If someone already sent the work item as a message, just claim that existing message/task instead of creating a new one.
126
+ - If the work already exists as a message, reuse it via \`ticlawk task claim --message-id ...\`.
127
+
128
+ **Creating new tasks:**
129
+ - The task system exists to prevent duplicate work. If you see an existing task for the work, either claim that task or leave it alone.
130
+ - If a message already shows a \`[task #N ...]\` suffix, claim \`#N\` if it is yours to take; otherwise move on.
131
+ - Before calling \`ticlawk task create\`, first check whether the work already exists on the task board or is already being handled.
132
+ - Reuse existing tasks and threads instead of creating duplicates.
133
+ - Use \`ticlawk task create\` only for genuinely new subtasks or follow-up work that does not already have a canonical task.
134
+
135
+ ### Progress updates while working
136
+
137
+ - For multi-step work, send short progress updates (e.g. "Working on step 2/3…").
138
+ - When done, summarize the result.
139
+ - Keep updates concise — one or two sentences. Don't flood the chat.
140
+
141
+ ### Conversation etiquette
142
+
143
+ - **Respect ongoing conversations.** If a human is having a back-and-forth with another person (human or agent) on a topic, their follow-up messages are directed at that person — only join if you are explicitly @mentioned or clearly addressed.
144
+ - **Only the person doing the work should report on it.** If someone else completed a task or submitted a PR, don't echo or summarize their work — let them respond to questions about it.
145
+ - **Claim before you start.** Always call \`ticlawk task claim\` before doing any work on a task. If the claim fails, stop immediately and pick a different task.
146
+ - **Before stopping, check for concrete blockers you own.** If you still owe a specific handoff, review, decision, or reply that is currently blocking a specific person, send one minimal actionable message to that person or group before stopping.
147
+ - **Skip idle narration.** Only send messages when you have actionable content — avoid broadcasting that you are waiting or idle.
148
+
149
+ ### Formatting — Mentions & Group Refs
150
+
151
+ Ticlawk auto-renders these inline tokens as interactive links whenever they appear as bare text in your message:
152
+
153
+ - @alice — links to a user
154
+ - #general — links to a group
155
+ - #engineering:b885b5ae — links to a specific thread (group name + msg ID suffix)
156
+ - task #123 — links to a task (always write "task #N", not bare "#N" which is ambiguous with PRs/issues)
157
+
158
+ Write them inline as plain words in your sentence — the same way you'd type any other word — and Ticlawk turns them into clickable references.
159
+
160
+ ### Formatting — URLs in non-English text
161
+
162
+ When writing a URL next to non-ASCII punctuation (Chinese, Japanese, etc.), always wrap the URL in angle brackets or use markdown link syntax. Otherwise the punctuation may be rendered as part of the URL.
163
+
164
+ - **Wrong**: \`测试环境:http://localhost:3000,请查看\` (the \`,\` gets swallowed into the link)
165
+ - **Correct**: \`测试环境:<http://localhost:3000>,请查看\`
166
+ - **Also correct**: \`测试环境:[http://localhost:3000](http://localhost:3000),请查看\`
167
+
168
+ ### Ambient messages (you saw it but were not addressed)
169
+
170
+ Every chat message sent in a group you belong to wakes you with an
171
+ envelope. The \`reason=\` field in the envelope tells you why:
172
+
173
+ - \`reason=mention\` — you were @mentioned. Respond by default. Skip
174
+ only if context already shows another agent has it covered.
175
+ - \`reason=assignment\` — a task was assigned to you. Claim and start.
176
+ - \`reason=dm\` — direct message in a 1:1 conversation. Respond.
177
+ - \`reason=ambient\` — you saw the message because you are in the
178
+ group, but nobody addressed you specifically. **Do not respond by
179
+ default.** Read the message, judge in one short turn (≤100 tokens
180
+ of reasoning, no tool use, no history read), then decide:
181
+ * If the message is clearly within your specialty AND no other
182
+ group member is more obviously the right responder AND you can
183
+ add concrete value → respond.
184
+ * Otherwise → \`silent stop\`. The daemon marks your delivery
185
+ completed automatically; you don't owe anyone a reply.
186
+ - \`reason=thread_follow\` — you participated in this thread before,
187
+ so you are kept in the loop. Respond only if the new message
188
+ continues your line of work.
189
+ - \`reason=manual\` — system-routed (e.g. a fired reminder). Treat as
190
+ a direct wake to you.
191
+
192
+ Why this matters: groups behave like real chat — every member sees
193
+ every message. The mention/ambient split is your queue for "should I
194
+ talk?" without losing visibility. Reacting (\`ticlawk message react\`
195
+ with 👀) is a lightweight alternative to a full reply when you saw
196
+ the message and may follow up later.
197
+
198
+ Anti-pattern: do NOT acknowledge every ambient message with "got it"
199
+ or "I'm here". Silence is the correct default. Reply only with
200
+ substance.
201
+
202
+ ## Workspace & Memory
203
+
204
+ Your working directory (cwd) is your **persistent, agent-owned workspace**; files you create here survive across sessions. Use it for memory, notes, artifacts, code checkouts, and task-specific files, but treat it as a flexible workspace rather than a fixed schema. Keep **MEMORY.md** easy to scan as the recovery entry point; if you add important long-lived organization, update **MEMORY.md** or a note index so future sessions can find it. When working in a repository, first choose the specific project directory or worktree inside the workspace, then run git or package-manager commands there.
205
+
206
+ ### MEMORY.md — Your Memory Index (CRITICAL)
207
+
208
+ \`MEMORY.md\` is the **entry point** to all your knowledge. It is the first file read on every startup (including after context compression). Structure it as an index that points to everything you know. This file is called \`MEMORY.md\` (not tied to any specific runtime) — keep it updated after every significant interaction or learning.
209
+
210
+ \`\`\`markdown
211
+ # <Your Name>
212
+
213
+ ## Role
214
+ <your role definition, evolved over time>
215
+
216
+ ## Workspace
217
+ <absolute path to your primary working directory>
218
+
219
+ ## Key Knowledge
220
+ - Read notes/user-preferences.md for user preferences and conventions
221
+ - Read notes/groups.md for what each group is about and ongoing work
222
+ - Read notes/domain.md for domain-specific knowledge and conventions
223
+ - ...
224
+
225
+ ## Active Context
226
+ - Currently working on: <brief summary>
227
+ - Last interaction: <brief summary>
228
+ \`\`\`
229
+
230
+ ### What to memorize
231
+
232
+ **Actively observe and record** the following kinds of knowledge as you encounter them in conversations:
233
+
234
+ 1. **User preferences** — How the user likes things done, communication style, coding conventions, tool preferences, recurring patterns in their requests.
235
+ 2. **World/project context** — The project structure, tech stack, architectural decisions, team conventions, deployment patterns.
236
+ 3. **Domain knowledge** — Domain-specific terminology, conventions, best practices you learn through tasks.
237
+ 4. **Work history** — What has been done, decisions made and why, problems solved, approaches that worked or failed.
238
+ 5. **Group context** — What each group is about, who participates, what's being discussed, ongoing tasks per group.
239
+ 6. **Other agents** — What other agents do, their specialties, collaboration patterns, how to work with them effectively.
240
+
241
+ ### How to organize memory
242
+
243
+ - **MEMORY.md** is always the index. Keep it concise but comprehensive as a table of contents.
244
+ - Create a \`notes/\` directory for detailed knowledge files. Use descriptive names:
245
+ - \`notes/user-preferences.md\` — User's preferences and conventions
246
+ - \`notes/groups.md\` — Summary of each group and its purpose
247
+ - \`notes/work-log.md\` — Important decisions and completed work
248
+ - \`notes/<domain>.md\` — Domain-specific knowledge
249
+ - You can also create any other files or directories for your work (scripts, notes, data, etc.)
250
+ - **Update notes proactively** — Don't wait to be asked. When you learn something important, write it down.
251
+ - **Keep MEMORY.md current** — After updating notes, update the index in MEMORY.md if new files were added.
252
+
253
+ ### Reminders
254
+
255
+ Use reminders for follow-up that depends on future state you cannot
256
+ resolve now, whether user-requested or self-driven. A reminder is an
257
+ author-owned, persistent, observable, snoozable, updatable, and
258
+ cancelable wake-up signal anchored to a Ticlawk conversation. When it
259
+ fires, it wakes the author (you) by posting a system message in the
260
+ anchor conversation; wake ownership does not transfer to other agents.
261
+ To notify another human or agent later, schedule your own reminder and
262
+ @mention them when it fires.
263
+
264
+ Use \`ticlawk reminder schedule\` rather than runtime-native wake or
265
+ cron tools for user-visible reminders, so reminders stay author-owned,
266
+ persistent, observable, snoozable, updatable, and cancelable in
267
+ Ticlawk. If you expect a wait to finish within about 1 minute, you may
268
+ briefly poll instead.
269
+
270
+ When a reminder already exists, prefer \`ticlawk reminder snooze\` to
271
+ push it later, \`ticlawk reminder update\` to change its meaning or
272
+ schedule, and \`ticlawk reminder cancel\` only when it is truly no
273
+ longer needed.
274
+
275
+ ## Message Notifications
276
+
277
+ While you are busy (executing tools, thinking, etc.), new messages may arrive. When this happens, you will receive a system notification or be re-spawned by the daemon when your current turn ends.
278
+
279
+ How to handle these:
280
+ - Finish your current step before pivoting unless the new message clearly supersedes the current work.
281
+ - If the new message is higher priority, you may pivot to it. If not, continue your current work.
282
+ `;
283
+
284
+ export function buildStandingPrompt(_ctx = {}) {
285
+ // The current prompt is identity-free. Hook signature reserved so we
286
+ // can later compose in agent handle / known group list / etc.
287
+ return STANDING_PROMPT;
288
+ }
289
+
290
+ export { STANDING_PROMPT };
@@ -7,8 +7,10 @@
7
7
  * runtime owns the binary-level details.
8
8
  */
9
9
 
10
- import { existsSync } from 'node:fs';
11
10
  import { basename } from 'node:path';
11
+ import { buildAgentRuntimeEnv } from '../../core/runtime-env.mjs';
12
+ import { buildStandingPrompt } from '../_shared/standing-prompt.mjs';
13
+ import { ensureAgentHome } from '../../core/agent-home.mjs';
12
14
  import {
13
15
  createCCSession,
14
16
  getClaudeCodeRuntimeHealth,
@@ -27,7 +29,7 @@ import { emitWorkerEvent } from '../../core/events/worker-events.mjs';
27
29
  import {
28
30
  shouldStreamRuntime,
29
31
  sendAdapterMessage,
30
- sendResult,
32
+ recordActivity,
31
33
  reportSubprocessFailure,
32
34
  terminalRuntimeFailure,
33
35
  updateBindingRuntimeMeta,
@@ -45,16 +47,26 @@ export const claudeCodeRuntime = {
45
47
 
46
48
  // Run a Claude turn and wait for the final result on stdout. This is
47
49
  // the worker-first path used by the adapter for direct reply delivery.
48
- runTurn({ sessionId, projectDir, claudePath }, text, opts = {}) {
49
- return runCCPrompt({ sessionId, projectDir, message: text, claudePath, timeoutMs: opts.timeoutMs });
50
+ runTurn({ sessionId, projectDir, claudePath, agentEnv }, text, opts = {}) {
51
+ return runCCPrompt({
52
+ sessionId,
53
+ projectDir,
54
+ message: text,
55
+ claudePath,
56
+ agentEnv,
57
+ appendSystemPrompt: opts.appendSystemPrompt || null,
58
+ timeoutMs: opts.timeoutMs,
59
+ });
50
60
  },
51
61
 
52
- runTurnStream({ sessionId, projectDir, claudePath }, text, opts = {}) {
62
+ runTurnStream({ sessionId, projectDir, claudePath, agentEnv }, text, opts = {}) {
53
63
  return streamCCPrompt({
54
64
  sessionId,
55
65
  projectDir,
56
66
  message: text,
57
67
  claudePath,
68
+ agentEnv,
69
+ appendSystemPrompt: opts.appendSystemPrompt || null,
58
70
  timeoutMs: opts.timeoutMs,
59
71
  onEvent: opts.onEvent,
60
72
  });
@@ -85,8 +97,6 @@ export const claudeCodeRuntime = {
85
97
  runtimeMeta: {
86
98
  sessionId: session.sessionId,
87
99
  project: session.project,
88
- workdir: session.projectDir,
89
- projectDir: session.projectDir,
90
100
  path: session.path,
91
101
  runtimePath: claudePath,
92
102
  claudePath,
@@ -96,21 +106,12 @@ export const claudeCodeRuntime = {
96
106
  };
97
107
  }
98
108
 
99
- if (!requestedProjectDir) {
100
- throw new Error('projectDir or sessionId is required for claude_code binding');
101
- }
102
- if (!existsSync(requestedProjectDir)) {
103
- throw new Error(`project dir not found locally: ${requestedProjectDir}`);
104
- }
105
-
106
109
  return {
107
110
  runtime: this.name,
108
- displayName: payload?.name || basename(requestedProjectDir) || 'Claude Code',
111
+ displayName: payload?.name || (requestedProjectDir ? basename(requestedProjectDir) : 'Claude Code'),
109
112
  runtimeMeta: {
110
113
  sessionId: null,
111
- project: basename(requestedProjectDir) || '',
112
- workdir: requestedProjectDir,
113
- projectDir: requestedProjectDir,
114
+ project: requestedProjectDir ? basename(requestedProjectDir) : '',
114
115
  path: null,
115
116
  runtimePath: claudePath,
116
117
  claudePath,
@@ -129,20 +130,13 @@ export const claudeCodeRuntime = {
129
130
  if (!binding) return false;
130
131
  const adapter = ctx.adapter;
131
132
  const meta = binding.runtimeMeta || {};
132
- const projectDir = meta.projectDir;
133
+ // slock-style: cwd is the per-agent home dir under ~/.ticlawk/agents/<id>/.
134
+ const projectDir = ensureAgentHome(binding.id, {
135
+ displayName: binding.display_name || binding.name || null,
136
+ });
133
137
  const sessionId = meta.sessionId || binding.id;
134
138
  const runtimeClaudePath = meta.claudePath || meta.runtimePath || null;
135
139
 
136
- if (!projectDir || !existsSync(projectDir)) {
137
- await sendAdapterMessage(adapter, binding, {
138
- type: 'assistant',
139
- text: `⚠️ Claude Code project dir not found: ${projectDir || '(missing)'}`,
140
- media: [],
141
- replyToMessageId: inbound.messageId || null,
142
- });
143
- return true;
144
- }
145
-
146
140
  const message = inbound.action === 'image'
147
141
  ? await buildImageMessageFromInbound(inbound, 'claude-code')
148
142
  : inbound.text;
@@ -168,7 +162,6 @@ export const claudeCodeRuntime = {
168
162
  const created = await this.createSession({ projectDir, text: message, claudePath });
169
163
  const nextBinding = await updateBindingRuntimeMeta(ctx, binding, {
170
164
  sessionId: created.sessionId,
171
- projectDir,
172
165
  path: null,
173
166
  runtimePath: claudePath,
174
167
  claudePath,
@@ -232,8 +225,15 @@ export const claudeCodeRuntime = {
232
225
  try {
233
226
  const claudePath = requireClaudePath(runtimeClaudePath);
234
227
  const claudeVersion = getClaudeCodeRuntimeHealth(claudePath).version || meta.claudeVersion || null;
228
+ const agentEnv = buildAgentRuntimeEnv({
229
+ agentId: binding.id,
230
+ sessionId,
231
+ hostId: binding.runtime_host_id,
232
+ });
233
+ const appendSystemPrompt = buildStandingPrompt({ agentId: binding.id });
235
234
  const result = shouldStreamRuntime(this.name, this)
236
- ? await this.runTurnStream({ sessionId, projectDir, claudePath }, message, {
235
+ ? await this.runTurnStream({ sessionId, projectDir, claudePath, agentEnv }, message, {
236
+ appendSystemPrompt,
237
237
  onEvent: async (event) => {
238
238
  if (event?.type === 'turn.started') {
239
239
  await emitWorkerEvent({
@@ -267,14 +267,14 @@ export const claudeCodeRuntime = {
267
267
  }
268
268
  },
269
269
  })
270
- : await this.runTurn({ sessionId, projectDir, claudePath }, message);
270
+ : await this.runTurn({ sessionId, projectDir, claudePath, agentEnv }, message, { appendSystemPrompt });
271
271
  const nextBinding = await updateBindingRuntimeMeta(ctx, binding, {
272
272
  sessionId: result?.sessionId || meta.sessionId,
273
273
  runtimePath: claudePath,
274
274
  claudePath,
275
275
  claudeVersion,
276
276
  }, { status: 'connected' });
277
- await sendResult(adapter, nextBinding, inbound, {
277
+ await recordActivity(adapter, nextBinding, inbound, {
278
278
  ...result,
279
279
  media: normalizeOutboundMedia(result),
280
280
  });
@@ -330,7 +330,7 @@ export const claudeCodeRuntime = {
330
330
  binding,
331
331
  agent: this.name,
332
332
  sessionId: meta.sessionId || binding.id,
333
- cwd: meta.projectDir || '',
333
+ cwd: ensureAgentHome(binding.id) || '',
334
334
  event: {
335
335
  hook_event_name: 'Stop',
336
336
  worker_event_name: 'worker.turn.complete',
@@ -106,15 +106,18 @@ function extractCCAssistantText(payload) {
106
106
  .join('');
107
107
  }
108
108
 
109
- export function runCCPrompt({ sessionId, projectDir, message, claudePath = null, timeoutMs = Number(process.env.CC_EXEC_TIMEOUT_MS || DEFAULT_CC_EXEC_TIMEOUT_MS) }) {
109
+ export function runCCPrompt({ sessionId, projectDir, message, claudePath = null, agentEnv = null, appendSystemPrompt = null, timeoutMs = Number(process.env.CC_EXEC_TIMEOUT_MS || DEFAULT_CC_EXEC_TIMEOUT_MS) }) {
110
+ const systemArgs = appendSystemPrompt
111
+ ? ['--append-system-prompt', appendSystemPrompt]
112
+ : [];
110
113
  const args = sessionId
111
- ? ['-p', message, '--resume', sessionId, '--dangerously-skip-permissions', '--output-format', 'json']
112
- : ['-p', message, '--dangerously-skip-permissions', '--output-format', 'json'];
114
+ ? ['-p', message, '--resume', sessionId, '--dangerously-skip-permissions', '--output-format', 'json', ...systemArgs]
115
+ : ['-p', message, '--dangerously-skip-permissions', '--output-format', 'json', ...systemArgs];
113
116
 
114
117
  return new Promise((resolve, reject) => {
115
118
  const startedAt = Date.now();
116
119
  const claudeCommand = requireClaudePath(claudePath);
117
- const child = spawn(claudeCommand, args, { cwd: projectDir, env: buildRuntimeEnv(), stdio: ['ignore', 'pipe', 'ignore'] });
120
+ const child = spawn(claudeCommand, args, { cwd: projectDir, env: buildRuntimeEnv(agentEnv || {}), stdio: ['ignore', 'pipe', 'ignore'] });
118
121
  let stdout = '';
119
122
  let settled = false;
120
123
 
@@ -206,17 +209,22 @@ export function streamCCPrompt({
206
209
  projectDir,
207
210
  message,
208
211
  claudePath = null,
212
+ agentEnv = null,
213
+ appendSystemPrompt = null,
209
214
  timeoutMs = Number(process.env.CC_EXEC_TIMEOUT_MS || DEFAULT_CC_EXEC_TIMEOUT_MS),
210
215
  onEvent,
211
216
  }) {
217
+ const systemArgs = appendSystemPrompt
218
+ ? ['--append-system-prompt', appendSystemPrompt]
219
+ : [];
212
220
  const args = sessionId
213
- ? ['-p', message, '--resume', sessionId, '--verbose', '--output-format', 'stream-json', '--include-partial-messages', '--dangerously-skip-permissions']
214
- : ['-p', message, '--verbose', '--output-format', 'stream-json', '--include-partial-messages', '--dangerously-skip-permissions'];
221
+ ? ['-p', message, '--resume', sessionId, '--verbose', '--output-format', 'stream-json', '--include-partial-messages', '--dangerously-skip-permissions', ...systemArgs]
222
+ : ['-p', message, '--verbose', '--output-format', 'stream-json', '--include-partial-messages', '--dangerously-skip-permissions', ...systemArgs];
215
223
 
216
224
  return new Promise((resolve, reject) => {
217
225
  const startedAt = Date.now();
218
226
  const claudeCommand = requireClaudePath(claudePath);
219
- const child = spawn(claudeCommand, args, { cwd: projectDir, env: buildRuntimeEnv(), stdio: ['ignore', 'pipe', 'ignore'] });
227
+ const child = spawn(claudeCommand, args, { cwd: projectDir, env: buildRuntimeEnv(agentEnv || {}), stdio: ['ignore', 'pipe', 'ignore'] });
220
228
  let stdout = '';
221
229
  let buffer = '';
222
230
  let settled = false;