ticlawk 0.1.16-dev.9 → 0.1.16

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.
Files changed (41) hide show
  1. package/README.md +15 -3
  2. package/bin/ticlawk.mjs +208 -21
  3. package/package.json +1 -1
  4. package/src/adapters/ticlawk/api.mjs +283 -48
  5. package/src/adapters/ticlawk/credentials.mjs +41 -1
  6. package/src/adapters/ticlawk/index.mjs +126 -121
  7. package/src/adapters/ticlawk/wake-client.mjs +1 -1
  8. package/src/cli/agent-commands.mjs +557 -18
  9. package/src/core/agent-cli-handlers.mjs +435 -18
  10. package/src/core/agent-home.mjs +81 -1
  11. package/src/core/argv.mjs +11 -1
  12. package/src/core/events/worker-events.mjs +32 -36
  13. package/src/core/http.mjs +119 -0
  14. package/src/core/runtime-contract.mjs +0 -1
  15. package/src/core/runtime-env.mjs +7 -0
  16. package/src/core/runtime-support.mjs +108 -77
  17. package/src/runtimes/_shared/agent-handbook.mjs +45 -0
  18. package/src/runtimes/_shared/brand.mjs +2 -0
  19. package/src/runtimes/_shared/goal-task-protocol.mjs +50 -0
  20. package/src/runtimes/_shared/handbook/BASICS.md +27 -0
  21. package/src/runtimes/_shared/handbook/COLLABORATION.md +37 -0
  22. package/src/runtimes/_shared/handbook/COMMUNICATION.md +55 -0
  23. package/src/runtimes/_shared/handbook/DM_SCOPE.md +13 -0
  24. package/src/runtimes/_shared/handbook/GOAL_AUTHORITY.md +46 -0
  25. package/src/runtimes/_shared/handbook/GOAL_TASK_CORE.md +43 -0
  26. package/src/runtimes/_shared/handbook/GROUP_ADMIN_SCOPE.md +21 -0
  27. package/src/runtimes/_shared/handbook/GROUP_MEMBER_SCOPE.md +15 -0
  28. package/src/runtimes/_shared/handbook/SURFACES.md +41 -0
  29. package/src/runtimes/_shared/handbook/TASK_WORKER.md +14 -0
  30. package/src/runtimes/_shared/standing-prompt.mjs +134 -278
  31. package/src/runtimes/_shared/wake-prompt.mjs +261 -0
  32. package/src/runtimes/claude-code/index.mjs +19 -46
  33. package/src/runtimes/claude-code/session.mjs +2 -7
  34. package/src/runtimes/codex/index.mjs +115 -63
  35. package/src/runtimes/codex/session.mjs +2 -12
  36. package/src/runtimes/openclaw/index.mjs +11 -24
  37. package/src/runtimes/opencode/index.mjs +38 -60
  38. package/src/runtimes/opencode/session.mjs +12 -12
  39. package/src/runtimes/pi/index.mjs +38 -60
  40. package/src/runtimes/pi/session.mjs +9 -6
  41. package/ticlawk.mjs +0 -30
@@ -7,7 +7,8 @@
7
7
  * and forwards to the ticlawk backend using the connector API key.
8
8
  *
9
9
  * Targets are parsed in the daemon (not on the wire to backend) so the
10
- * CLI can speak `#<group>` / `dm:@<user>` / `#<group>:<short-msg-id>`
10
+ * CLI can speak `#<group>` / `dm:<conversation-id>` / `dm:@<user>` /
11
+ * `#<group>:<short-msg-id>`
11
12
  * while backend keeps a flat conversation_id contract.
12
13
  */
13
14
 
@@ -34,7 +35,7 @@ export function invalidateServerInfoCache(actingAgentId = null) {
34
35
  }
35
36
 
36
37
  /**
37
- * Parse a target string into { conversationId, threadRootMsgId } using a
38
+ * Parse a target string into { conversationId, replyToMessageId } using a
38
39
  * cached server-info lookup. Returns null fields if the target cannot be
39
40
  * resolved; callers should treat that as a 404.
40
41
  *
@@ -43,29 +44,29 @@ export function invalidateServerInfoCache(actingAgentId = null) {
43
44
  * dm:@<handle> -> find DM conversation whose other member is <handle>
44
45
  * #<uuid> -> conversation_id = <uuid>
45
46
  * #<group-name> -> find group conversation by name
46
- * <foo>:<short-msg-id> -> thread under <foo>, root = first message whose
47
+ * <foo>:<short-msg-id> -> replies under <foo>, root = first message whose
47
48
  * id startsWith <short-msg-id>
48
49
  */
49
50
  export async function resolveTarget(actingAgentId, target) {
50
- if (!target) return { conversationId: null, threadRootMsgId: null, error: 'target is required' };
51
+ if (!target) return { conversationId: null, replyToMessageId: null, error: 'target is required' };
51
52
 
52
- // Strip optional thread suffix.
53
+ // Strip optional message-reply suffix.
53
54
  let base = target;
54
- let threadShort = null;
55
+ let replyToMessageId = null;
55
56
  const colonIdx = target.indexOf(':', target.startsWith('dm:') ? 3 : 1);
56
57
  if (colonIdx > 0 && colonIdx < target.length - 1) {
57
- threadShort = target.slice(colonIdx + 1);
58
+ replyToMessageId = target.slice(colonIdx + 1);
58
59
  base = target.slice(0, colonIdx);
59
60
  }
60
61
 
61
62
  if (/^[0-9a-f-]{36}$/i.test(base)) {
62
- return { conversationId: base, threadRootMsgId: threadShort, error: null };
63
+ return { conversationId: base, replyToMessageId, error: null };
63
64
  }
64
65
  if (base.startsWith('dm:') && /^[0-9a-f-]{36}$/i.test(base.slice(3))) {
65
- return { conversationId: base.slice(3), threadRootMsgId: threadShort, error: null };
66
+ return { conversationId: base.slice(3), replyToMessageId, error: null };
66
67
  }
67
68
  if (base.startsWith('#') && /^[0-9a-f-]{36}$/i.test(base.slice(1))) {
68
- return { conversationId: base.slice(1), threadRootMsgId: threadShort, error: null };
69
+ return { conversationId: base.slice(1), replyToMessageId, error: null };
69
70
  }
70
71
 
71
72
  const info = await getCachedServerInfo(actingAgentId);
@@ -76,19 +77,30 @@ export async function resolveTarget(actingAgentId, target) {
76
77
  const match = convs.find((c) =>
77
78
  c.type === 'dm' && (String(c.display_name || c.name || '').toLowerCase() === handle)
78
79
  );
79
- if (match) return { conversationId: match.id, threadRootMsgId: threadShort, error: null };
80
- return { conversationId: null, threadRootMsgId: null, error: `unknown dm target: ${target}` };
80
+ if (match) return { conversationId: match.id, replyToMessageId, error: null };
81
+ return { conversationId: null, replyToMessageId: null, error: `unknown dm target: ${target}` };
81
82
  }
82
83
  if (base.startsWith('#')) {
83
84
  const name = base.slice(1).toLowerCase();
84
85
  const match = convs.find((c) =>
85
86
  c.type === 'group' && (String(c.name || c.display_name || '').toLowerCase() === name)
86
87
  );
87
- if (match) return { conversationId: match.id, threadRootMsgId: threadShort, error: null };
88
- return { conversationId: null, threadRootMsgId: null, error: `unknown group target: ${target}` };
88
+ if (match) return { conversationId: match.id, replyToMessageId, error: null };
89
+
90
+ if (info?.agent?.is_cos) {
91
+ const workstreams = await api.listWorkstreams({ actingAgentId });
92
+ const workstreamMatch = workstreams.find((c) =>
93
+ String(c.name || c.display_name || '').toLowerCase() === name
94
+ );
95
+ if (workstreamMatch) {
96
+ return { conversationId: workstreamMatch.id, replyToMessageId, error: null };
97
+ }
98
+ }
99
+
100
+ return { conversationId: null, replyToMessageId: null, error: `unknown group target: ${target}` };
89
101
  }
90
102
 
91
- return { conversationId: null, threadRootMsgId: null, error: `invalid target syntax: ${target}` };
103
+ return { conversationId: null, replyToMessageId: null, error: `invalid target syntax: ${target}` };
92
104
  }
93
105
 
94
106
  function getActingAgentId(req, body = {}) {
@@ -109,6 +121,15 @@ function getRuntimeHostId(req, body = {}) {
109
121
  return null;
110
122
  }
111
123
 
124
+ function getCurrentConversationId(req, body = {}) {
125
+ const fromHeader = req.headers['x-ticlawk-current-conversation-id'];
126
+ if (typeof fromHeader === 'string' && fromHeader.trim()) return fromHeader.trim();
127
+ if (typeof body?.current_conversation_id === 'string' && body.current_conversation_id.trim()) {
128
+ return body.current_conversation_id.trim();
129
+ }
130
+ return null;
131
+ }
132
+
112
133
  function validateActingAgent(actingAgentId, ctx) {
113
134
  if (!actingAgentId) {
114
135
  return { ok: false, status: 400, error: 'TICLAWK_RUNTIME_AGENT_ID required (passed via X-Ticlawk-Acting-Agent-Id or body.acting_as_agent_id)' };
@@ -123,6 +144,16 @@ function validateActingAgent(actingAgentId, ctx) {
123
144
  return { ok: true };
124
145
  }
125
146
 
147
+ function validateAgentResponsePhase(metadata) {
148
+ const phase = metadata?.agent_response_phase;
149
+ if (phase == null) return { ok: true, phase: null };
150
+ const normalized = String(phase).trim().toLowerCase();
151
+ if (normalized === 'progress' || normalized === 'final') {
152
+ return { ok: true, phase: normalized };
153
+ }
154
+ return { ok: false, error: 'metadata.agent_response_phase must be progress or final' };
155
+ }
156
+
126
157
  export async function handleMessageSend(req, body, ctx) {
127
158
  const actingAgentId = getActingAgentId(req, body);
128
159
  const v = validateActingAgent(actingAgentId, ctx);
@@ -132,22 +163,45 @@ export async function handleMessageSend(req, body, ctx) {
132
163
  if (!text) return { status: 400, body: { error: 'text is required' } };
133
164
 
134
165
  let conversationId = body?.conversation_id || null;
135
- let threadRootMsgId = null;
166
+ let targetReplyToMessageId = null;
136
167
  if (!conversationId && body?.target) {
137
168
  const resolved = await resolveTarget(actingAgentId, String(body.target));
138
169
  if (resolved.error) {
139
170
  return { status: 404, body: { error: resolved.error } };
140
171
  }
141
172
  conversationId = resolved.conversationId;
142
- threadRootMsgId = resolved.threadRootMsgId;
173
+ targetReplyToMessageId = resolved.replyToMessageId;
143
174
  }
144
175
  if (!conversationId) {
145
176
  return { status: 400, body: { error: 'target or conversation_id is required' } };
146
177
  }
147
178
 
179
+ const currentConversationId = getCurrentConversationId(req, body);
180
+ if (currentConversationId && currentConversationId !== conversationId && !body?.allow_cross_target) {
181
+ debugLog('agent-cli', 'send.blocked-cross-target', {
182
+ actingAgentId,
183
+ currentConversationId,
184
+ conversationId,
185
+ target: body?.target || null,
186
+ });
187
+ return {
188
+ status: 409,
189
+ body: {
190
+ error: 'refusing to send to a different conversation from the current runtime turn',
191
+ current_conversation_id: currentConversationId,
192
+ target_conversation_id: conversationId,
193
+ hint: 'Use --allow-cross-target only for an intentional cross-conversation send.',
194
+ },
195
+ };
196
+ }
197
+
148
198
  const mediaAssetIds = Array.isArray(body?.media_asset_ids)
149
199
  ? body.media_asset_ids.map((v) => String(v).trim()).filter(Boolean)
150
200
  : [];
201
+ const metadata = body?.metadata;
202
+ const phaseRes = validateAgentResponsePhase(metadata);
203
+ if (!phaseRes.ok) return { status: 400, body: { error: phaseRes.error } };
204
+ if (metadata && phaseRes.phase) metadata.agent_response_phase = phaseRes.phase;
151
205
 
152
206
  try {
153
207
  const data = await api.sendAgentMessage({
@@ -155,15 +209,17 @@ export async function handleMessageSend(req, body, ctx) {
155
209
  conversationId,
156
210
  text,
157
211
  seenUpToSeq: body?.seen_up_to_seq,
158
- replyToMessageId: body?.reply_to_message_id || threadRootMsgId || null,
212
+ replyToMessageId: body?.reply_to_message_id || targetReplyToMessageId || null,
159
213
  runtimeHostId: getRuntimeHostId(req, body),
160
214
  mediaAssetIds,
215
+ metadata,
161
216
  });
162
217
  debugLog('agent-cli', 'send.ok', {
163
218
  actingAgentId,
164
219
  conversationId,
165
220
  messageId: data?.id,
166
221
  seq: data?.seq,
222
+ agentResponsePhase: phaseRes.phase,
167
223
  bodyChars: text.length,
168
224
  });
169
225
  return { status: 200, body: { ok: true, data } };
@@ -229,6 +285,7 @@ export async function handleTaskCreate(req, body, ctx) {
229
285
  conversationId,
230
286
  text,
231
287
  title: body?.title ?? null,
288
+ assignAgentId: body?.assign_agent_id || body?.assignee_agent_id || null,
232
289
  });
233
290
  debugLog('agent-cli', 'task.create', {
234
291
  actingAgentId,
@@ -716,6 +773,366 @@ export async function handleGroupMembersRemove(req, body, ctx) {
716
773
  }
717
774
  }
718
775
 
776
+ export async function handleWorkstreamCreate(req, body, ctx) {
777
+ const actingAgentId = getActingAgentId(req, body);
778
+ const v = validateActingAgent(actingAgentId, ctx);
779
+ if (!v.ok) return { status: v.status, body: { error: v.error } };
780
+ const name = String(body?.name || '').trim();
781
+ if (!name) return { status: 400, body: { error: 'name is required' } };
782
+ try {
783
+ const data = await api.createWorkstream({
784
+ actingAgentId,
785
+ name,
786
+ description: body?.description || null,
787
+ charter: body?.charter ?? null,
788
+ memberAgentIds: Array.isArray(body?.member_agent_ids) ? body.member_agent_ids : [],
789
+ });
790
+ invalidateServerInfoCache(actingAgentId);
791
+ debugLog('agent-cli', 'workstream.create', {
792
+ actingAgentId, conversationId: data?.conversation?.id,
793
+ });
794
+ return { status: 200, body: data };
795
+ } catch (err) {
796
+ return { status: err?.status || 500, body: { error: err?.message || 'workstream create failed' } };
797
+ }
798
+ }
799
+
800
+ export async function handleWorkstreamDelete(req, body, ctx) {
801
+ const actingAgentId = getActingAgentId(req, body);
802
+ const v = validateActingAgent(actingAgentId, ctx);
803
+ if (!v.ok) return { status: v.status, body: { error: v.error } };
804
+ let conversationId = body?.conversation_id || null;
805
+ if (!conversationId && body?.target) {
806
+ const resolved = await resolveTarget(actingAgentId, String(body.target));
807
+ if (resolved.error) return { status: 404, body: { error: resolved.error } };
808
+ conversationId = resolved.conversationId;
809
+ }
810
+ if (!conversationId) return { status: 400, body: { error: 'target or conversation_id is required' } };
811
+ try {
812
+ const data = await api.deleteWorkstream({ actingAgentId, conversationId });
813
+ invalidateServerInfoCache(actingAgentId);
814
+ return { status: 200, body: data };
815
+ } catch (err) {
816
+ return { status: err?.status || 500, body: { error: err?.message || 'workstream delete failed' } };
817
+ }
818
+ }
819
+
820
+ export async function handleWorkstreamList(req, query, ctx) {
821
+ const actingAgentId = getActingAgentId(req, query);
822
+ const v = validateActingAgent(actingAgentId, ctx);
823
+ if (!v.ok) return { status: v.status, body: { error: v.error } };
824
+ try {
825
+ const data = await api.listWorkstreams({ actingAgentId });
826
+ return { status: 200, body: { data } };
827
+ } catch (err) {
828
+ return { status: err?.status || 500, body: { error: err?.message || 'workstream list failed' } };
829
+ }
830
+ }
831
+
832
+ export async function handleAgentList(req, query, ctx) {
833
+ const actingAgentId = getActingAgentId(req, query);
834
+ const v = validateActingAgent(actingAgentId, ctx);
835
+ if (!v.ok) return { status: v.status, body: { error: v.error } };
836
+ try {
837
+ const data = await api.listAgentSlots({ actingAgentId });
838
+ return { status: 200, body: { data } };
839
+ } catch (err) {
840
+ return { status: err?.status || 500, body: { error: err?.message || 'agent list failed' } };
841
+ }
842
+ }
843
+
844
+ export async function handleAgentCreate(req, body, ctx) {
845
+ const actingAgentId = getActingAgentId(req, body);
846
+ const v = validateActingAgent(actingAgentId, ctx);
847
+ if (!v.ok) return { status: v.status, body: { error: v.error } };
848
+ const name = String(body?.name || '').trim();
849
+ const runtime = String(body?.runtime || '').trim();
850
+ if (!name) return { status: 400, body: { error: 'name is required' } };
851
+ if (!runtime) return { status: 400, body: { error: 'runtime is required' } };
852
+ try {
853
+ const data = await api.createAgentSlot({
854
+ actingAgentId,
855
+ name,
856
+ runtime,
857
+ description: body?.description || null,
858
+ displayName: body?.display_name || null,
859
+ model: body?.model || null,
860
+ });
861
+ return { status: 200, body: data };
862
+ } catch (err) {
863
+ return { status: err?.status || 500, body: { error: err?.message || 'agent create failed' } };
864
+ }
865
+ }
866
+
867
+ export async function handleAgentDelete(req, body, ctx) {
868
+ const actingAgentId = getActingAgentId(req, body);
869
+ const v = validateActingAgent(actingAgentId, ctx);
870
+ if (!v.ok) return { status: v.status, body: { error: v.error } };
871
+ const agentId = String(body?.agent_id || '').trim();
872
+ if (!agentId) return { status: 400, body: { error: 'agent_id is required' } };
873
+ try {
874
+ const data = await api.archiveAgentSlot({ actingAgentId, agentId });
875
+ return { status: 200, body: data };
876
+ } catch (err) {
877
+ return { status: err?.status || 500, body: { error: err?.message || 'agent delete failed' } };
878
+ }
879
+ }
880
+
881
+ export async function handleServiceCreate(req, body, ctx) {
882
+ const actingAgentId = getActingAgentId(req, body);
883
+ const v = validateActingAgent(actingAgentId, ctx);
884
+ if (!v.ok) return { status: v.status, body: { error: v.error } };
885
+ const name = String(body?.name || '').trim();
886
+ if (!name) return { status: 400, body: { error: 'name is required' } };
887
+ if (!body?.endpoint_config || typeof body.endpoint_config !== 'object') {
888
+ return { status: 400, body: { error: 'endpoint_config is required' } };
889
+ }
890
+ try {
891
+ const data = await api.createService({
892
+ actingAgentId, name,
893
+ description: body?.description || null,
894
+ contractSchema: body?.contract_schema ?? null,
895
+ endpointConfig: body.endpoint_config,
896
+ });
897
+ return { status: 200, body: data };
898
+ } catch (err) {
899
+ return { status: err?.status || 500, body: { error: err?.message || 'service create failed' } };
900
+ }
901
+ }
902
+
903
+ export async function handleServiceUpdate(req, body, ctx) {
904
+ const actingAgentId = getActingAgentId(req, body);
905
+ const v = validateActingAgent(actingAgentId, ctx);
906
+ if (!v.ok) return { status: v.status, body: { error: v.error } };
907
+ const serviceId = String(body?.service_id || '').trim();
908
+ if (!serviceId) return { status: 400, body: { error: 'service_id is required' } };
909
+ const patch = {};
910
+ if ('description' in (body || {})) patch.description = body.description;
911
+ if ('contract_schema' in (body || {})) patch.contract_schema = body.contract_schema;
912
+ if ('endpoint_config' in (body || {})) patch.endpoint_config = body.endpoint_config;
913
+ if ('status' in (body || {})) patch.status = body.status;
914
+ try {
915
+ const data = await api.updateService({ actingAgentId, serviceId, ...patch });
916
+ return { status: 200, body: data };
917
+ } catch (err) {
918
+ return { status: err?.status || 500, body: { error: err?.message || 'service update failed' } };
919
+ }
920
+ }
921
+
922
+ export async function handleServiceDelete(req, body, ctx) {
923
+ const actingAgentId = getActingAgentId(req, body);
924
+ const v = validateActingAgent(actingAgentId, ctx);
925
+ if (!v.ok) return { status: v.status, body: { error: v.error } };
926
+ const serviceId = String(body?.service_id || '').trim();
927
+ if (!serviceId) return { status: 400, body: { error: 'service_id is required' } };
928
+ try {
929
+ const data = await api.deleteService({ actingAgentId, serviceId });
930
+ return { status: 200, body: data };
931
+ } catch (err) {
932
+ return { status: err?.status || 500, body: { error: err?.message || 'service delete failed' } };
933
+ }
934
+ }
935
+
936
+ export async function handleServiceList(req, query, ctx) {
937
+ const actingAgentId = getActingAgentId(req, query);
938
+ const v = validateActingAgent(actingAgentId, ctx);
939
+ if (!v.ok) return { status: v.status, body: { error: v.error } };
940
+ try {
941
+ const data = await api.listServices({ actingAgentId });
942
+ return { status: 200, body: { data } };
943
+ } catch (err) {
944
+ return { status: err?.status || 500, body: { error: err?.message || 'service list failed' } };
945
+ }
946
+ }
947
+
948
+ export async function handleServiceInfo(req, query, ctx) {
949
+ const actingAgentId = getActingAgentId(req, query);
950
+ const v = validateActingAgent(actingAgentId, ctx);
951
+ if (!v.ok) return { status: v.status, body: { error: v.error } };
952
+ const name = String(query?.name || '').trim();
953
+ if (!name) return { status: 400, body: { error: 'name is required' } };
954
+ try {
955
+ const data = await api.getServiceInfo({ actingAgentId, name });
956
+ return { status: 200, body: data };
957
+ } catch (err) {
958
+ return { status: err?.status || 500, body: { error: err?.message || 'service info failed' } };
959
+ }
960
+ }
961
+
962
+ export async function handleServiceCall(req, body, ctx) {
963
+ const actingAgentId = getActingAgentId(req, body);
964
+ const v = validateActingAgent(actingAgentId, ctx);
965
+ if (!v.ok) return { status: v.status, body: { error: v.error } };
966
+ const name = String(body?.name || '').trim();
967
+ if (!name) return { status: 400, body: { error: 'name is required' } };
968
+ try {
969
+ const data = await api.callService({
970
+ actingAgentId, name,
971
+ input: body?.input ?? null,
972
+ });
973
+ return { status: 200, body: data };
974
+ } catch (err) {
975
+ return { status: err?.status || 500, body: { error: err?.message || 'service call failed' } };
976
+ }
977
+ }
978
+
979
+ export async function handleBriefingGet(req, query, ctx) {
980
+ const actingAgentId = getActingAgentId(req, query);
981
+ const v = validateActingAgent(actingAgentId, ctx);
982
+ if (!v.ok) return { status: v.status, body: { error: v.error } };
983
+ const briefingId = String(query?.id || '').trim();
984
+ if (!briefingId) return { status: 400, body: { error: 'id is required' } };
985
+ try {
986
+ const data = await api.getBriefing({ actingAgentId, briefingId });
987
+ return { status: 200, body: data };
988
+ } catch (err) {
989
+ return { status: err?.status || 500, body: { error: err?.message || 'briefing get failed' } };
990
+ }
991
+ }
992
+
993
+ export async function handleBriefingPublish(req, body, ctx) {
994
+ const actingAgentId = getActingAgentId(req, body);
995
+ const v = validateActingAgent(actingAgentId, ctx);
996
+ if (!v.ok) return { status: v.status, body: { error: v.error } };
997
+ const bodyText = typeof body?.body_text === 'string' && body.body_text.trim() ? body.body_text.trim() : null;
998
+ const attachmentAssetId = typeof body?.attachment_asset_id === 'string' && body.attachment_asset_id.trim()
999
+ ? body.attachment_asset_id.trim()
1000
+ : null;
1001
+ const responseMode = typeof body?.response_mode === 'string' && body.response_mode.trim()
1002
+ ? body.response_mode.trim().toLowerCase()
1003
+ : 'info';
1004
+ if (!bodyText) {
1005
+ return { status: 400, body: { error: 'body_text is required' } };
1006
+ }
1007
+ if (bodyText && bodyText.length > 140) {
1008
+ return { status: 400, body: { error: 'body_text must be ≤140 chars' } };
1009
+ }
1010
+ if (!['info', 'approval'].includes(responseMode)) {
1011
+ return { status: 400, body: { error: 'response_mode must be info or approval' } };
1012
+ }
1013
+ const currentConversationId = getCurrentConversationId(req, body);
1014
+ try {
1015
+ const data = await api.publishBriefing({
1016
+ actingAgentId,
1017
+ bodyText,
1018
+ attachmentAssetId,
1019
+ currentConversationId,
1020
+ responseMode,
1021
+ });
1022
+ return { status: 200, body: data };
1023
+ } catch (err) {
1024
+ return { status: err?.status || 500, body: { error: err?.message || 'briefing publish failed' } };
1025
+ }
1026
+ }
1027
+
1028
+ export async function handleCredentialRequest(req, body, ctx) {
1029
+ const actingAgentId = getActingAgentId(req, body);
1030
+ const v = validateActingAgent(actingAgentId, ctx);
1031
+ if (!v.ok) return { status: v.status, body: { error: v.error } };
1032
+ const name = String(body?.name || '').trim();
1033
+ if (!name) return { status: 400, body: { error: 'name is required' } };
1034
+ let workstreamId = body?.workstream_id || null;
1035
+ if (!workstreamId && body?.target) {
1036
+ const resolved = await resolveTarget(actingAgentId, String(body.target));
1037
+ if (resolved.error) return { status: 404, body: { error: resolved.error } };
1038
+ workstreamId = resolved.conversationId;
1039
+ }
1040
+ try {
1041
+ const data = await api.requestCredential({
1042
+ actingAgentId,
1043
+ name,
1044
+ description: body?.description || null,
1045
+ workstreamId,
1046
+ });
1047
+ return { status: 200, body: data };
1048
+ } catch (err) {
1049
+ return { status: err?.status || 500, body: { error: err?.message || 'credential request failed' } };
1050
+ }
1051
+ }
1052
+
1053
+ export async function handleWorkstreamDashboardSet(req, body, ctx) {
1054
+ const actingAgentId = getActingAgentId(req, body);
1055
+ const v = validateActingAgent(actingAgentId, ctx);
1056
+ if (!v.ok) return { status: v.status, body: { error: v.error } };
1057
+ let conversationId = body?.conversation_id || null;
1058
+ if (!conversationId && body?.target) {
1059
+ const resolved = await resolveTarget(actingAgentId, String(body.target));
1060
+ if (resolved.error) return { status: 404, body: { error: resolved.error } };
1061
+ conversationId = resolved.conversationId;
1062
+ }
1063
+ if (!conversationId) return { status: 400, body: { error: 'target or conversation_id is required' } };
1064
+ const payload = { actingAgentId, conversationId };
1065
+ if ('data_json' in (body || {})) payload.dataJson = body.data_json;
1066
+ if ('html_template' in (body || {})) payload.htmlTemplate = body.html_template;
1067
+ try {
1068
+ const data = await api.setWorkstreamDashboard(payload);
1069
+ return { status: 200, body: data };
1070
+ } catch (err) {
1071
+ return { status: err?.status || 500, body: { error: err?.message || 'dashboard set failed' } };
1072
+ }
1073
+ }
1074
+
1075
+ export async function handleWorkstreamDashboardGet(req, query, ctx) {
1076
+ const actingAgentId = getActingAgentId(req, query);
1077
+ const v = validateActingAgent(actingAgentId, ctx);
1078
+ if (!v.ok) return { status: v.status, body: { error: v.error } };
1079
+ let conversationId = query?.conversation_id || null;
1080
+ if (!conversationId && query?.target) {
1081
+ const resolved = await resolveTarget(actingAgentId, String(query.target));
1082
+ if (resolved.error) return { status: 404, body: { error: resolved.error } };
1083
+ conversationId = resolved.conversationId;
1084
+ }
1085
+ if (!conversationId) return { status: 400, body: { error: 'target or conversation_id is required' } };
1086
+ try {
1087
+ const data = await api.getWorkstreamDashboard({ actingAgentId, conversationId });
1088
+ return { status: 200, body: data };
1089
+ } catch (err) {
1090
+ return { status: err?.status || 500, body: { error: err?.message || 'dashboard get failed' } };
1091
+ }
1092
+ }
1093
+
1094
+ export async function handleWorkstreamCharterGet(req, query, ctx) {
1095
+ const actingAgentId = getActingAgentId(req, query);
1096
+ const v = validateActingAgent(actingAgentId, ctx);
1097
+ if (!v.ok) return { status: v.status, body: { error: v.error } };
1098
+ let conversationId = query?.conversation_id || null;
1099
+ if (!conversationId && query?.target) {
1100
+ const resolved = await resolveTarget(actingAgentId, String(query.target));
1101
+ if (resolved.error) return { status: 404, body: { error: resolved.error } };
1102
+ conversationId = resolved.conversationId;
1103
+ }
1104
+ if (!conversationId) return { status: 400, body: { error: 'target or conversation_id is required' } };
1105
+ try {
1106
+ const data = await api.getWorkstreamCharter({ actingAgentId, conversationId });
1107
+ return { status: 200, body: data };
1108
+ } catch (err) {
1109
+ return { status: err?.status || 500, body: { error: err?.message || 'charter get failed' } };
1110
+ }
1111
+ }
1112
+
1113
+ export async function handleWorkstreamCharterSet(req, body, ctx) {
1114
+ const actingAgentId = getActingAgentId(req, body);
1115
+ const v = validateActingAgent(actingAgentId, ctx);
1116
+ if (!v.ok) return { status: v.status, body: { error: v.error } };
1117
+ let conversationId = body?.conversation_id || null;
1118
+ if (!conversationId && body?.target) {
1119
+ const resolved = await resolveTarget(actingAgentId, String(body.target));
1120
+ if (resolved.error) return { status: 404, body: { error: resolved.error } };
1121
+ conversationId = resolved.conversationId;
1122
+ }
1123
+ if (!conversationId) return { status: 400, body: { error: 'target or conversation_id is required' } };
1124
+ const charter = typeof body?.charter === 'string' ? body.charter : null;
1125
+ try {
1126
+ const data = await api.setWorkstreamCharter({ actingAgentId, conversationId, charter });
1127
+ debugLog('agent-cli', 'workstream.charter.set', {
1128
+ actingAgentId, conversationId, len: charter?.length ?? 0,
1129
+ });
1130
+ return { status: 200, body: data };
1131
+ } catch (err) {
1132
+ return { status: err?.status || 500, body: { error: err?.message || 'charter set failed' } };
1133
+ }
1134
+ }
1135
+
719
1136
  export async function handleServerInfo(req, query, ctx) {
720
1137
  const actingAgentId = getActingAgentId(req, query);
721
1138
  const v = validateActingAgent(actingAgentId, ctx);
@@ -7,9 +7,10 @@
7
7
  * lives in cwd, agent reads it via `cat MEMORY.md`.
8
8
  */
9
9
 
10
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
10
+ import { existsSync, lstatSync, mkdirSync, readFileSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';
11
11
  import { join } from 'node:path';
12
12
  import { AF_HOME } from './config.mjs';
13
+ import { buildAgentHandbookFiles, LEGACY_HANDBOOK_FILE_NAMES } from '../runtimes/_shared/agent-handbook.mjs';
13
14
 
14
15
  export const AF_AGENTS_DIR = join(AF_HOME, 'agents');
15
16
 
@@ -37,9 +38,88 @@ export function ensureAgentHome(agentId, { displayName } = {}) {
37
38
  if (!existsSync(memoryPath)) {
38
39
  writeFileSync(memoryPath, buildInitialMemoryMd({ displayName, home }), 'utf8');
39
40
  }
41
+ writeManagedHandbookFiles(home);
42
+ ensureSkillSymlinks(home);
40
43
  return home;
41
44
  }
42
45
 
46
+ function writeManagedHandbookFiles(home) {
47
+ removeLegacyManagedHandbookFiles(home);
48
+ for (const { name, content } of buildAgentHandbookFiles()) {
49
+ const path = join(home, name);
50
+ try {
51
+ let stat = null;
52
+ try { stat = lstatSync(path); } catch { /* not present */ }
53
+ if (stat && !stat.isFile()) continue;
54
+ const next = `${content.trim()}\n`;
55
+ if (stat) {
56
+ const current = readFileSync(path, 'utf8');
57
+ if (current === next) continue;
58
+ }
59
+ writeFileSync(path, next, { encoding: 'utf8', mode: 0o600 });
60
+ } catch (err) {
61
+ console.warn(`[agent-home] failed to write ${path}: ${err?.message || err}`);
62
+ }
63
+ }
64
+ }
65
+
66
+ function removeLegacyManagedHandbookFiles(home) {
67
+ for (const name of LEGACY_HANDBOOK_FILE_NAMES) {
68
+ const path = join(home, name);
69
+ try {
70
+ const stat = lstatSync(path);
71
+ if (!stat.isFile()) continue;
72
+ unlinkSync(path);
73
+ } catch (err) {
74
+ if (err?.code === 'ENOENT') continue;
75
+ console.warn(`[agent-home] failed to remove legacy handbook ${path}: ${err?.message || err}`);
76
+ }
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Cross-runtime skill discovery: every runtime (Claude Code, Codex,
82
+ * opencode, pi, openclaw) auto-discovers SKILL.md under at least one of
83
+ * .claude/skills/, .codex/skills/, .opencode/skills/, .pi/skills/, or
84
+ * .agents/skills/. We pin everything to a single source-of-truth
85
+ * directory (.agents/skills/) and symlink the rest so a skill written
86
+ * once is visible to every runtime without sync machinery.
87
+ *
88
+ * .pi and .opencode skip the symlink — both natively scan
89
+ * .agents/skills/ in addition to their own folder.
90
+ *
91
+ * No migration / no recovery: if the target path already exists as a
92
+ * real dir or wrong-target symlink, we leave it alone. The user (or a
93
+ * future agent) resolves it manually. See cos_impl.md §一.不为错误兜底.
94
+ */
95
+ function ensureSkillSymlinks(home) {
96
+ const realRoot = join(home, '.agents', 'skills');
97
+ mkdirSync(realRoot, { recursive: true });
98
+
99
+ const links = [
100
+ { dir: join(home, '.claude'), name: 'skills', target: '../.agents/skills' },
101
+ { dir: join(home, '.codex'), name: 'skills', target: '../.agents/skills' },
102
+ // openclaw expects skills/ at the home root
103
+ { dir: home, name: 'skills', target: '.agents/skills' },
104
+ ];
105
+
106
+ for (const { dir, name, target } of links) {
107
+ mkdirSync(dir, { recursive: true });
108
+ const linkPath = join(dir, name);
109
+ let stat = null;
110
+ try { stat = lstatSync(linkPath); } catch { /* not present */ }
111
+ if (stat) continue; // path already exists — do not touch
112
+ try {
113
+ symlinkSync(target, linkPath, 'dir');
114
+ } catch (err) {
115
+ // Best-effort: an EEXIST race or platform that disallows symlinks
116
+ // gets logged but doesn't fail spawn. Skills just won't be visible
117
+ // for that runtime via this folder.
118
+ console.warn(`[agent-home] failed to symlink ${linkPath} -> ${target}: ${err?.message || err}`);
119
+ }
120
+ }
121
+ }
122
+
43
123
  function buildInitialMemoryMd({ displayName, home }) {
44
124
  const lines = [
45
125
  `# ${displayName || 'Agent'}`,
package/src/core/argv.mjs CHANGED
@@ -29,7 +29,17 @@ export function parseOptionArgs(argv = []) {
29
29
  const value = inlineValue !== undefined
30
30
  ? inlineValue
31
31
  : argv[i + 1] && !argv[i + 1].startsWith('-') ? argv[++i] : true;
32
- args[rawKey] = value;
32
+ // Repeated flags collect into an array so `--attach a --attach b`
33
+ // surfaces as ['a','b'] to callers that expect repeatable input
34
+ // (--attach on message send, --member on group create, etc).
35
+ // First occurrence stays scalar so single-value callers don't
36
+ // have to learn array-or-string.
37
+ if (Object.prototype.hasOwnProperty.call(args, rawKey)) {
38
+ const existing = args[rawKey];
39
+ args[rawKey] = Array.isArray(existing) ? [...existing, value] : [existing, value];
40
+ } else {
41
+ args[rawKey] = value;
42
+ }
33
43
  continue;
34
44
  }
35
45
  args._.push(arg);