Repository navigation
Expand file tree
/
Copy pathtools.ts
More file actions
334 lines (327 loc) · 13.7 KB
/
Copy pathtools.ts
File metadata and controls
334 lines (327 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import { tool } from 'ai';
import { z } from 'zod';
import type { GoalOutcome, SimSession } from '@/src/shared/sim/session';
import type { ActionHint, Observation, Sense } from '@/src/shared/state';
import { GAIT, MARK_LIMIT, MARK_NAME_MAX, MARK_NOTE_MAX } from '@/src/shared/config';
import { kindOf } from '@/src/shared/kinds';
import { VIEW_DISTANCE } from '@/src/shared/world';
import type { MemoryApi } from '@/src/client/journal/diary';
import type { Landmark } from '@/src/shared/landmarks';
const thought = z.string().describe('用第一人称说一句你在做什么,20 字以内。');
function call<T extends z.ZodRawShape>(shape: T) {
return z.object({ description: thought, ...shape });
}
/** Compact new observations without modifying any previously sent messages. */
function agentObservation(observation: Observation) {
return {
...observation,
terrain: observation.terrain.map(({ by, ...direction }) =>
by === 'clear' ? direction : { ...direction, by },
),
entities: observation.entities.map(({ y: _y, stage, properties, ...entity }) => ({
...entity,
...(stage === 0 ? {} : { stage }),
...(properties.length === 0 ? {} : { properties }),
})),
};
}
function agentLandmarks(landmarks: readonly Landmark[]) {
return landmarks.map(({ name, x, z, ground }) => ({
name,
x,
z,
ground: Math.round(ground * 100) / 100,
}));
}
export function spiderTools(session: SimSession, memory?: MemoryApi) {
const hintFor = (outcome: GoalOutcome, self: Sense): ActionHint | undefined => {
switch (outcome.reason) {
case 'blocked':
return {
code: 'blocked',
message: self.ways?.length
? '前方被固体挡住了。self.ways 是可走的坐标,用 go 的 point 走过去,不要顶同一个方向。'
: '前方被固体挡住了。换一个 x、z,用 go 绕开。',
next: 'go',
};
case 'steep':
return {
code: 'steep',
message: '这段坡太陡。用 self.ways 里的坐标换一条路,或先 set_height 再走。',
next: self.ways?.length ? 'go' : 'set_height',
};
case 'no-path':
return {
code: 'no-path',
message: '没有可走的路线。换一个目标,或先 observe。',
next: 'observe',
};
case 'out-of-reach':
return {
code: 'out-of-reach',
message: '目标还不在够得着的范围内。用 go,mode 填 id,走到它旁边。',
next: 'go',
};
case 'not-found':
return {
code: 'stale-target',
message: '这个 id 已经不在当前世界里,先 observe 获取新的 id。',
next: 'observe',
};
case 'nothing-to-eat':
case 'nothing-to-carry':
return {
code: 'no-target',
message: '当前附近没有符合条件的对象,不要重复调用同一个动作。',
next: 'observe',
};
case 'full':
return {
code: 'carry-full',
message: '牵引的物品已经达到上限。先用 act 的 release、drop 或 store 放下一件。',
next: 'act',
};
case 'no-water':
return self.water
? {
code: 'no-water',
message: '附近没有够得着的水。按 self.water 的 x、z 用 go 走过去。',
next: 'go',
}
: {
code: 'no-water',
message: '附近没有水。先 observe,再按看见的水走过去。',
next: 'observe',
};
case 'cancelled':
case 'timeout':
return {
code: outcome.reason,
message: '行动没有完成,先 observe 确认当前状态再决定下一步。',
next: 'observe',
};
default:
return undefined;
}
};
const finish = (outcome: GoalOutcome, state?: 'position' | 'heading' | 'height') => {
const { halt: _halt, ...rest } = outcome;
const blocked =
rest.reason === 'blocked' || rest.reason === 'steep' || rest.reason === 'no-path';
if (rest.ok && !state) return rest;
const self = session.sense(blocked);
const hint = hintFor(rest, self);
return {
...rest,
...(state || blocked
? {
self: {
...(state === 'position' || blocked ? { x: self.x, z: self.z } : {}),
...(state === 'heading' || state === 'position' || blocked
? { heading: self.heading }
: {}),
...(state === 'height' || blocked ? { height: self.height } : {}),
...(blocked ? { ways: self.ways } : {}),
},
}
: {}),
...(rest.reason === 'no-water' ? { self: { water: self.water } } : {}),
...(hint ? { hint } : {}),
};
};
const tools = {
observe: tool({
description:
'观察周围地形和物体,并查看家园地标。草丛会缩短视野,抬高身体能看得更远;inReach 表示够得着。',
inputSchema: call({
distance: z
.number()
.min(0)
.max(VIEW_DISTANCE)
.optional()
.describe(`看多远,最多 ${VIEW_DISTANCE}。不填就尽量看远。`),
}),
execute: async ({ distance }) => {
const observation = session.observe(distance ?? VIEW_DISTANCE);
const world = session.worldInfo();
const hint =
observation.self.cover && observation.view < VIEW_DISTANCE
? {
code: 'view-limited-by-cover',
message: `遮蔽物把视野缩短到了 ${observation.view}。先用 set_height 抬高身体,再 observe。`,
next: 'set_height',
}
: !session.lamp && world.view < 0.9 && observation.view < VIEW_DISTANCE
? {
code: 'view-limited-by-light',
message: `现在是${world.clock.localTime},视野只有 ${observation.view}。用 lamp 把灯打开,能看得更远,但到不了白天。`,
next: 'lamp',
}
: session.lamp && world.view < 0.9 && observation.view < VIEW_DISTANCE
? {
code: 'view-limited-by-light',
message: `灯已经开了,视野是 ${observation.view},还是比白天近。靠近后再 observe。`,
next: 'go',
}
: observation.beyond > 0 || observation.hidden > 0
? {
code: 'partial-observation',
message: `这次只看到了视野内的对象,还有 ${observation.beyond} 个在视野外、${observation.hidden} 个被遮挡。移动或抬高身体后再 observe。`,
next: 'go',
}
: undefined;
return {
ok: true,
world,
near: session.near(),
landmarks: agentLandmarks(session.landmarks()),
...(hint ? { hint } : {}),
observation: agentObservation(observation),
};
},
}),
go: tool({
description:
'移动或转身,一次只做一件事。point 走到 x、z,自动翻过可攀爬的矮地物,绕开挡路的高障碍。id 走到对象旁边并面向它。heading 或 degrees 只转身。',
inputSchema: z.discriminatedUnion('mode', [
call({
mode: z.literal('point').describe('走到一个坐标。'),
x: z.number().describe('目标 x。'),
z: z.number().describe('目标 z。'),
fast: z.boolean().optional().describe('跑起来。'),
}),
call({
mode: z.literal('id').describe('走到一个对象旁边。'),
id: z.string().describe('对象 id。'),
standoff: z.number().min(0).optional().describe('停在多远。不填就贴近。'),
fast: z.boolean().optional().describe('跑起来。'),
}),
call({
mode: z.literal('heading').describe('转到一个绝对朝向。'),
heading: z.number().min(-180).max(180).describe('绝对朝向,0 是 -Z,范围 -180..180。'),
}),
call({
mode: z.literal('degrees').describe('相对现在转身。'),
degrees: z.number().describe('相对角度,顺时针为正。'),
}),
]),
execute: async (input) => {
if (input.mode === 'point')
return finish(await session.moveTo(input.x, input.z, input.fast ?? false), 'position');
if (input.mode === 'id')
return finish(
await session.approach(input.id, input.standoff, input.fast ?? false),
'position',
);
if (input.mode === 'heading') return finish(await session.turnTo(input.heading), 'heading');
return finish(await session.turn(input.degrees), 'heading');
},
}),
mark: tool({
description: `记录、查看或删除有名字的地点,最多 ${MARK_LIMIT} 个。列表还包含家园内置地标。`,
inputSchema: call({
command: z.enum(['add', 'list', 'remove']).describe('add、list 或 remove。'),
name: z.string().optional().describe(`地点名,${MARK_NAME_MAX} 字以内。add、remove 要填。`),
note: z.string().optional().describe(`备注,${MARK_NOTE_MAX} 字以内。`),
}),
execute: async ({ command, name, note }) => {
if (command === 'list')
return {
ok: true,
marks: session.marks(),
landmarks: agentLandmarks(session.landmarks()),
};
if (!name) return finish({ ok: false, reason: 'need-name' });
if (command === 'add') return finish(session.mark(name, note));
return finish(session.forgetMark(name));
},
}),
act: tool({
description: `吃、牵引、松手、放下、存进巢、喝水或睡觉。eat、pick_up、release、drop、store 要带 id,最多牵引 ${kindOf(session.actor.entity.kind)?.tether?.limit ?? 0} 件。`,
inputSchema: z.discriminatedUnion('verb', [
call({
verb: z.literal('eat').describe('吃附近或背上的食物。'),
id: z.string().describe('对象 id。'),
}),
call({
verb: z.literal('pick_up').describe('搬起附近能搬的东西。'),
id: z.string().describe('对象 id。'),
}),
call({
verb: z.literal('release').describe('在当前位置松开蛛丝,物品保留当前速度。'),
id: z.string().describe('正在牵引的物品 id。'),
}),
call({
verb: z.literal('drop').describe('松开蛛丝,把东西放在面前。'),
id: z.string().describe('物品 id。'),
}),
call({
verb: z.literal('store').describe('把蛛丝牵着的东西放进巢里。'),
id: z.string().describe('物品 id。'),
}),
call({
verb: z.literal('drink').describe('在水边喝水。'),
}),
call({
verb: z.literal('sleep').describe('在巢里睡觉,醒来还在原地。'),
}),
]),
execute: async (input) => {
if (input.verb === 'eat') return finish(await session.eat(input.id));
if (input.verb === 'pick_up') return finish(await session.pickUp(input.id));
if (input.verb === 'release') return finish(session.release(input.id));
if (input.verb === 'drop') return finish(session.drop(input.id));
if (input.verb === 'store') return finish(session.store(input.id));
if (input.verb === 'drink') return finish(session.drink());
return finish(await session.sleep());
},
}),
lamp: tool({
description:
'开关背上的灯。灯在八条腿连着的背上。天越暗视野越短,开灯能补回一部分,但到不了白天。晚上看不清就打开。',
inputSchema: call({
on: z.boolean().describe('true 开灯,false 关灯。'),
}),
execute: async ({ on }) => {
session.setLamp(on);
return { ok: true, on };
},
}),
set_height: tool({
description: '抬高或放低身体,改变视线和越坡能力,不移动位置。',
inputSchema: call({
level: z
.number()
.min(GAIT.heightMin)
.max(GAIT.heightMax)
.describe(`离地高度,${GAIT.heightMin} 到 ${GAIT.heightMax}。`),
}),
execute: async ({ level }) => finish(await session.setHeight(level), 'height'),
}),
...(memory
? {
memory: tool({
description:
'按需管理跨天记忆:list 列目录,get 读某天,write 写某天。由你决定何时使用。写之前先 get,保留已有内容;只记录有依据的经历和用户明确表达的偏好。',
inputSchema: call({
command: z.enum(['list', 'get', 'write']).describe('list、get 或 write。'),
date: z.string().optional().describe('YYYY-MM-DD。get、write 要填。'),
line: z.string().optional().describe('目录上的一句。'),
noted: z.string().optional().describe('要留下的话。'),
summary: z.string().optional().describe('当天摘要。'),
}),
execute: async ({ command, date, line, noted, summary }) => {
if (command === 'list') return { ok: true, pages: await memory.list() };
if (!date) return { ok: false, reason: 'need-date' };
if (command === 'get') {
const page = await memory.get(date);
return page ? { ok: true, ...page } : { ok: false, reason: 'not-found', date };
}
return { ok: true, ...(await memory.write({ date, line, noted, summary })) };
},
}),
}
: {}),
};
return tools;
}