@joe-broadhead/opencode-mem 0.7.1 → 0.8.0
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.
- package/README.md +28 -3
- package/docs/agent-protocol.md +166 -170
- package/package.json +125 -2
- package/skills/mem-usage/SKILL.md +443 -357
- package/src/bootstrap.js +10 -2
- package/src/call-shapes.js +30 -0
- package/src/config.js +39 -0
- package/src/curation.js +45 -9
- package/src/protocol.js +12 -11
- package/src/recall.js +85 -24
- package/src/records-store.js +207 -0
- package/src/records.js +440 -0
- package/src/runtime.js +38 -2
- package/src/skills.js +10 -2
- package/src/tools/commitments.js +209 -0
- package/src/tools/index.js +9 -2
- package/src/tools/knowledge.js +19 -3
- package/src/tools/memory.js +96 -16
- package/src/tools/recall.js +5 -1
- package/src/tools/shared.js +1 -1
- package/src/tools/spaces.js +3 -3
- package/src/tools/status.js +1 -1
- package/src/tools/wiki.js +166 -30
- package/src/views/contracts.js +54 -1
- package/src/views/rpc.js +48 -2
- package/views/commitments.html +226 -0
- package/views/memory.html +77 -1
package/src/records.js
ADDED
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Commitments: things someone will do, with a time or a trigger, kept as a
|
|
3
|
+
* structured record with a state (docs/design/memory-value-design.md §7).
|
|
4
|
+
*
|
|
5
|
+
* Atoms cannot hold this: they cannot be updated, upstream assigns their type,
|
|
6
|
+
* and `work_task` atoms are withheld from recall by design. So each space
|
|
7
|
+
* keeps one reserved, never-ingested wiki, "Memory records", holding one file,
|
|
8
|
+
* `commitments.json`:
|
|
9
|
+
*
|
|
10
|
+
* { "marker": "opencode-mem:records v1", "version": 7, "items": [ … ] }
|
|
11
|
+
*
|
|
12
|
+
* This module is pure: parse, validate, apply a change, merge a change into a
|
|
13
|
+
* newer copy, and render the Due list and the list answer. The I/O and the
|
|
14
|
+
* concurrency check live in `records-store.js`.
|
|
15
|
+
*/
|
|
16
|
+
import { isInstructionShaped } from "./curation.js"
|
|
17
|
+
import { neutralizeFenceClosers, oneLine } from "./util.js"
|
|
18
|
+
|
|
19
|
+
export const RECORDS_WIKI = "Memory records"
|
|
20
|
+
export const RECORDS_FILE = "commitments.json"
|
|
21
|
+
export const RECORDS_MARKER = "opencode-mem:records v1"
|
|
22
|
+
|
|
23
|
+
export const STATES = Object.freeze(["open", "done", "cancelled"])
|
|
24
|
+
export const MAX_WHAT_CHARS = 300
|
|
25
|
+
export const MAX_TRIGGER_CHARS = 200
|
|
26
|
+
/** Closed commitments are kept this long, then dropped on the next write. */
|
|
27
|
+
export const CLOSED_RETENTION_DAYS = 90
|
|
28
|
+
/** One space's file stays small: the Due list and the views read it whole. */
|
|
29
|
+
export const MAX_ITEMS = 500
|
|
30
|
+
/**
|
|
31
|
+
* The Due list holds overdue items and those due within this many working
|
|
32
|
+
* days after today. The design's kill rule ("the Due list nags") sets it to 0:
|
|
33
|
+
* overdue and today only.
|
|
34
|
+
*/
|
|
35
|
+
export const DUE_WORKING_DAYS = 2
|
|
36
|
+
export const DUE_MAX_LINES = 5
|
|
37
|
+
|
|
38
|
+
const DATE = /^(\d{4})-(\d{2})-(\d{2})$/
|
|
39
|
+
const DATE_TIME = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,9})?)?(Z|[+-]\d{2}:\d{2})$/
|
|
40
|
+
const SLUG = /^[a-z0-9][a-z0-9-]{0,79}$/
|
|
41
|
+
const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
|
|
42
|
+
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
|
|
43
|
+
|
|
44
|
+
/** An empty records file. */
|
|
45
|
+
export function emptyRecords() {
|
|
46
|
+
return { marker: RECORDS_MARKER, version: 0, items: [] }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Read a records file. A missing file is an empty record set; a file that is
|
|
51
|
+
* not ours (no marker) or not JSON is an error, so a write never replaces
|
|
52
|
+
* something it does not understand.
|
|
53
|
+
*
|
|
54
|
+
* @param {string | null | undefined} text
|
|
55
|
+
* @returns {{ records?: { marker: string, version: number, items: any[] }, error?: string }}
|
|
56
|
+
*/
|
|
57
|
+
export function parseRecords(text) {
|
|
58
|
+
if (text === null || text === undefined || String(text).trim() === "") return { records: emptyRecords() }
|
|
59
|
+
let parsed
|
|
60
|
+
try {
|
|
61
|
+
parsed = JSON.parse(String(text))
|
|
62
|
+
} catch {
|
|
63
|
+
return { error: "the records file is not valid JSON" }
|
|
64
|
+
}
|
|
65
|
+
if (!parsed || typeof parsed !== "object" || parsed.marker !== RECORDS_MARKER) {
|
|
66
|
+
return { error: "the records file has no opencode-mem records marker" }
|
|
67
|
+
}
|
|
68
|
+
const version = Number.isInteger(parsed.version) && parsed.version >= 0 ? parsed.version : 0
|
|
69
|
+
const items = (Array.isArray(parsed.items) ? parsed.items : []).filter(
|
|
70
|
+
(item) => item && typeof item === "object" && typeof item.id === "string" && typeof item.what === "string",
|
|
71
|
+
)
|
|
72
|
+
return { records: { marker: RECORDS_MARKER, version, items } }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The file's text; the marker is the first key, as a share's marker is its first line. */
|
|
76
|
+
export function serializeRecords(records) {
|
|
77
|
+
return `${JSON.stringify({ marker: RECORDS_MARKER, version: records.version, items: records.items }, null, 2)}\n`
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** True when a file's text is a records file (used to keep it out of mem_wiki). */
|
|
81
|
+
export function isRecordsText(text) {
|
|
82
|
+
try {
|
|
83
|
+
return JSON.parse(String(text))?.marker === RECORDS_MARKER
|
|
84
|
+
} catch {
|
|
85
|
+
return false
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function validCalendarDate(year, month, day) {
|
|
90
|
+
const date = new Date(Date.UTC(year, month - 1, day))
|
|
91
|
+
return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Validate a due value: a date (`YYYY-MM-DD`, by the end of that day in the
|
|
96
|
+
* agent's zone) or a date-time with an offset. The tool cannot know what
|
|
97
|
+
* "Friday" meant, so it refuses anything else rather than guess.
|
|
98
|
+
*
|
|
99
|
+
* @returns {{ due?: string, error?: string }}
|
|
100
|
+
*/
|
|
101
|
+
export function validateDue(value) {
|
|
102
|
+
const text = String(value ?? "").trim()
|
|
103
|
+
const date = text.match(DATE)
|
|
104
|
+
if (date) {
|
|
105
|
+
if (!validCalendarDate(Number(date[1]), Number(date[2]), Number(date[3]))) {
|
|
106
|
+
return { error: `${text} is not a calendar date; due is YYYY-MM-DD, for example 2026-11-06` }
|
|
107
|
+
}
|
|
108
|
+
return { due: text }
|
|
109
|
+
}
|
|
110
|
+
const time = text.match(DATE_TIME)
|
|
111
|
+
if (time && validCalendarDate(Number(time[1]), Number(time[2]), Number(time[3])) && Number(time[4]) < 24 && Number(time[5]) < 60) {
|
|
112
|
+
if (Number.isFinite(Date.parse(text))) return { due: text }
|
|
113
|
+
}
|
|
114
|
+
return {
|
|
115
|
+
error: `due must be a date, YYYY-MM-DD (for example 2026-11-06), or a date-time with an offset (for example 2026-11-06T15:00:00+00:00); got ${JSON.stringify(oneLine(text, 60))}. Resolve "Friday" or "next week" against today first.`,
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** The calendar day an instant falls on in a zone, as `YYYY-MM-DD`. */
|
|
120
|
+
export function dayIn(instant, zone) {
|
|
121
|
+
const parts = Object.fromEntries(
|
|
122
|
+
new Intl.DateTimeFormat("en-CA", { timeZone: zone, year: "numeric", month: "2-digit", day: "2-digit" })
|
|
123
|
+
.formatToParts(new Date(instant))
|
|
124
|
+
.map((part) => [part.type, part.value]),
|
|
125
|
+
)
|
|
126
|
+
return `${parts.year}-${parts.month}-${parts.day}`
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** The day a commitment is due, in the zone: a bare date is itself. */
|
|
130
|
+
export function dueDay(due, zone) {
|
|
131
|
+
if (!due) return ""
|
|
132
|
+
return DATE.test(due) ? due : dayIn(Date.parse(due), zone)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function addDays(day, count) {
|
|
136
|
+
const [year, month, date] = day.split("-").map(Number)
|
|
137
|
+
const next = new Date(Date.UTC(year, month - 1, date + count))
|
|
138
|
+
return next.toISOString().slice(0, 10)
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function weekday(day) {
|
|
142
|
+
const [year, month, date] = day.split("-").map(Number)
|
|
143
|
+
return new Date(Date.UTC(year, month - 1, date)).getUTCDay()
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** The n-th working day (Monday to Friday) after `day`; 0 is `day` itself. */
|
|
147
|
+
export function workingDaysAfter(day, count) {
|
|
148
|
+
let current = day
|
|
149
|
+
let left = count
|
|
150
|
+
while (left > 0) {
|
|
151
|
+
current = addDays(current, 1)
|
|
152
|
+
const dow = weekday(current)
|
|
153
|
+
if (dow !== 0 && dow !== 6) left -= 1
|
|
154
|
+
}
|
|
155
|
+
return current
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** "Fri 6 Nov", the form every answer and view echoes back. */
|
|
159
|
+
export function formatDay(day) {
|
|
160
|
+
if (!DATE.test(String(day ?? ""))) return String(day ?? "")
|
|
161
|
+
const [, month, date] = day.split("-").map(Number)
|
|
162
|
+
return `${WEEKDAYS[weekday(day)]} ${date} ${MONTHS[month - 1]}`
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** "Fri 6 Nov" or "Fri 6 Nov 15:00 (+00:00)" for a date-time. */
|
|
166
|
+
export function formatDue(due, zone) {
|
|
167
|
+
if (!due) return ""
|
|
168
|
+
if (DATE.test(due)) return formatDay(due)
|
|
169
|
+
const day = dueDay(due, zone)
|
|
170
|
+
const time = new Intl.DateTimeFormat("en-GB", { timeZone: zone, hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).format(
|
|
171
|
+
new Date(Date.parse(due)),
|
|
172
|
+
)
|
|
173
|
+
return `${formatDay(day)} ${time}`
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** A new id: `cmt_` and eight base32 characters. */
|
|
177
|
+
export function newCommitmentId(random = Math.random) {
|
|
178
|
+
const alphabet = "abcdefghijklmnopqrstuvwxyz234567"
|
|
179
|
+
let id = "cmt_"
|
|
180
|
+
for (let index = 0; index < 8; index += 1) id += alphabet[Math.floor(random() * alphabet.length)]
|
|
181
|
+
return id
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Validate the text fields of an add or update. `what` and `trigger` are
|
|
186
|
+
* stored and pushed into the system prompt, so they pass the instruction
|
|
187
|
+
* guard; they are not held to the status guard (a commitment is the home for
|
|
188
|
+
* exactly what that guard refuses).
|
|
189
|
+
*
|
|
190
|
+
* @returns {{ fields?: Record<string, any>, error?: string }}
|
|
191
|
+
*/
|
|
192
|
+
export function validateFields(input, { requireWhat = false } = {}) {
|
|
193
|
+
const fields = {}
|
|
194
|
+
const has = (key) => input?.[key] !== undefined && input?.[key] !== null
|
|
195
|
+
if (requireWhat || has("what")) {
|
|
196
|
+
const what = oneLine(input?.what ?? "", MAX_WHAT_CHARS + 1).trim()
|
|
197
|
+
if (!what) return { error: "what is required: what will be done, starting with a verb (\"Send the Q4 numbers to Ama\")" }
|
|
198
|
+
if (what.length > MAX_WHAT_CHARS) return { error: `what is limited to ${MAX_WHAT_CHARS} characters` }
|
|
199
|
+
fields.what = what
|
|
200
|
+
}
|
|
201
|
+
if (has("owner")) {
|
|
202
|
+
const owner = oneLine(input.owner, 80).trim()
|
|
203
|
+
if (!owner) return { error: 'owner is "user", "agent", or a person\'s name' }
|
|
204
|
+
fields.owner = /^(user|me|you)$/i.test(owner) ? "user" : /^agent$/i.test(owner) ? "agent" : owner
|
|
205
|
+
}
|
|
206
|
+
if (has("due")) {
|
|
207
|
+
if (String(input.due).trim() === "") fields.due = ""
|
|
208
|
+
else {
|
|
209
|
+
const due = validateDue(input.due)
|
|
210
|
+
if (due.error) return { error: due.error }
|
|
211
|
+
fields.due = due.due
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
if (has("trigger")) {
|
|
215
|
+
const trigger = oneLine(input.trigger, MAX_TRIGGER_CHARS + 1).trim()
|
|
216
|
+
if (trigger.length > MAX_TRIGGER_CHARS) return { error: `trigger is limited to ${MAX_TRIGGER_CHARS} characters` }
|
|
217
|
+
fields.trigger = trigger
|
|
218
|
+
}
|
|
219
|
+
if (has("project")) {
|
|
220
|
+
const project = String(input.project).trim().toLowerCase()
|
|
221
|
+
if (project && !SLUG.test(project)) return { error: 'project is the page slug: lower-case words joined by hyphens, for example "checkout-v3"' }
|
|
222
|
+
fields.project = project
|
|
223
|
+
}
|
|
224
|
+
if (has("link")) fields.link = oneLine(input.link, 300).trim()
|
|
225
|
+
if (has("state")) {
|
|
226
|
+
const state = String(input.state).trim().toLowerCase()
|
|
227
|
+
if (!STATES.includes(state)) return { error: `state must be one of ${STATES.join(", ")}` }
|
|
228
|
+
fields.state = state
|
|
229
|
+
}
|
|
230
|
+
for (const key of ["what", "trigger", "owner", "link"]) {
|
|
231
|
+
if (fields[key] && isInstructionShaped(fields[key])) {
|
|
232
|
+
return { error: `${key} contains an instruction. Memory is a data channel and never carries commands.` }
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return { fields }
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Lower-case words only: "Send the Q4 numbers to Ama." equals "send the q4 numbers to Ama". */
|
|
239
|
+
export function normalText(value) {
|
|
240
|
+
return String(value ?? "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim()
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function sameText(left, right) {
|
|
244
|
+
return normalText(left) !== "" && normalText(left) === normalText(right)
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const STOP_WORDS = new Set("the a an and or to of for on in at by with from my our your me us".split(" "))
|
|
248
|
+
|
|
249
|
+
/** Open commitments whose words mostly overlap `what`: possible duplicates to show the agent. */
|
|
250
|
+
export function similarOpen(items, what, exceptId) {
|
|
251
|
+
const words = (value) => new Set(normalText(value).split(" ").filter((word) => word.length > 1 && !STOP_WORDS.has(word)))
|
|
252
|
+
const target = words(what)
|
|
253
|
+
if (target.size === 0) return []
|
|
254
|
+
return (items ?? []).filter((item) => {
|
|
255
|
+
if (item.state !== "open" || item.id === exceptId) return false
|
|
256
|
+
const other = words(item.what)
|
|
257
|
+
let shared = 0
|
|
258
|
+
for (const word of target) if (other.has(word)) shared += 1
|
|
259
|
+
return shared / Math.max(target.size, other.size) >= 0.5
|
|
260
|
+
})
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Drop empty optional fields so a cleared field is gone, not an empty string. */
|
|
264
|
+
function compact(item) {
|
|
265
|
+
const out = {}
|
|
266
|
+
for (const [key, value] of Object.entries(item)) {
|
|
267
|
+
if (value === "" || value === undefined || value === null) continue
|
|
268
|
+
out[key] = value
|
|
269
|
+
}
|
|
270
|
+
return out
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Closed commitments older than the retention window are dropped. A closed
|
|
275
|
+
* item with no `closed` date uses `updated`.
|
|
276
|
+
*/
|
|
277
|
+
export function prune(items, today) {
|
|
278
|
+
const cutoff = addDays(today, -CLOSED_RETENTION_DAYS)
|
|
279
|
+
return items.filter((item) => item.state === "open" || String(item.closed ?? item.updated ?? today) >= cutoff)
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* One change, applied to a record set. A change is replayable: it names its
|
|
284
|
+
* target by id, so the same change can be applied again to a newer copy of
|
|
285
|
+
* the file that someone else wrote in between (`records-store.js`).
|
|
286
|
+
*
|
|
287
|
+
* @param {{ items: any[] }} records
|
|
288
|
+
* @param {{ action: "add" | "update" | "delete", id: string, fields?: Record<string, any> }} change
|
|
289
|
+
* @param {{ today: string, session?: string }} context
|
|
290
|
+
* @returns {{ items?: any[], item?: any, error?: string, unchanged?: boolean }}
|
|
291
|
+
*/
|
|
292
|
+
export function applyChange(records, change, context) {
|
|
293
|
+
const items = records.items.slice()
|
|
294
|
+
const index = items.findIndex((item) => item.id === change.id)
|
|
295
|
+
if (change.action === "add") {
|
|
296
|
+
if (index >= 0) return { items, item: items[index], unchanged: true }
|
|
297
|
+
// The same open commitment, worded the same, is not added twice.
|
|
298
|
+
const same = items.find((item) => item.state === "open" && sameText(item.what, change.fields.what))
|
|
299
|
+
if (same) return { items, item: same, unchanged: true, duplicate: true }
|
|
300
|
+
if (items.filter((item) => item.state === "open").length >= MAX_ITEMS) {
|
|
301
|
+
return { error: `this space already holds ${MAX_ITEMS} open commitments; close or delete some first` }
|
|
302
|
+
}
|
|
303
|
+
const item = compact({
|
|
304
|
+
id: change.id,
|
|
305
|
+
what: change.fields.what,
|
|
306
|
+
owner: change.fields.owner ?? "user",
|
|
307
|
+
due: change.fields.due,
|
|
308
|
+
trigger: change.fields.trigger,
|
|
309
|
+
state: "open",
|
|
310
|
+
project: change.fields.project,
|
|
311
|
+
link: change.fields.link,
|
|
312
|
+
created: context.today,
|
|
313
|
+
updated: context.today,
|
|
314
|
+
session: context.session,
|
|
315
|
+
})
|
|
316
|
+
items.push(item)
|
|
317
|
+
return { items: prune(items, context.today), item }
|
|
318
|
+
}
|
|
319
|
+
if (index < 0) return { error: `no commitment ${oneLine(change.id, 40)} in this space` }
|
|
320
|
+
if (change.action === "delete") {
|
|
321
|
+
const [item] = items.splice(index, 1)
|
|
322
|
+
return { items: prune(items, context.today), item }
|
|
323
|
+
}
|
|
324
|
+
const before = items[index]
|
|
325
|
+
const next = { ...before, ...change.fields, updated: context.today }
|
|
326
|
+
if (change.fields.state && change.fields.state !== before.state) {
|
|
327
|
+
if (change.fields.state === "open") delete next.closed
|
|
328
|
+
else next.closed = context.today
|
|
329
|
+
}
|
|
330
|
+
const item = compact(next)
|
|
331
|
+
items[index] = item
|
|
332
|
+
return { items: prune(items, context.today), item }
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** Open first, then by due day (overdue first), undated last, then by creation. */
|
|
336
|
+
export function sortItems(items, zone) {
|
|
337
|
+
const rank = (item) => (item.state === "open" ? 0 : 1)
|
|
338
|
+
return items.slice().sort((a, b) => {
|
|
339
|
+
if (rank(a) !== rank(b)) return rank(a) - rank(b)
|
|
340
|
+
const left = dueDay(a.due, zone) || "9999-99-99"
|
|
341
|
+
const right = dueDay(b.due, zone) || "9999-99-99"
|
|
342
|
+
if (left !== right) return left < right ? -1 : 1
|
|
343
|
+
return String(a.created ?? "").localeCompare(String(b.created ?? ""))
|
|
344
|
+
})
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** How a person or the agent reads the owner. */
|
|
348
|
+
function ownerLabel(owner) {
|
|
349
|
+
return oneLine(owner || "user", 80)
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** Text from a record that is about to be shown: fence-safe, one line. */
|
|
353
|
+
function shown(value, max) {
|
|
354
|
+
return neutralizeFenceClosers(oneLine(value, max))
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* When a commitment is due, relative to today: "overdue since Mon 2 Nov",
|
|
359
|
+
* "today", or "Fri 6 Nov".
|
|
360
|
+
*/
|
|
361
|
+
export function dueLabel(item, today, zone) {
|
|
362
|
+
const day = dueDay(item.due, zone)
|
|
363
|
+
if (!day) return ""
|
|
364
|
+
if (day < today) return `overdue since ${formatDay(day)}`
|
|
365
|
+
if (day === today) return DATE.test(item.due) ? "today" : `today ${formatDue(item.due, zone).split(" ").pop()}`
|
|
366
|
+
return formatDue(item.due, zone)
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* The pinned block's Due section: overdue items and those due within the next
|
|
371
|
+
* `DUE_WORKING_DAYS` working days, oldest first, at most `DUE_MAX_LINES`
|
|
372
|
+
* lines, then a count of the other open items. It carries no time of day, so
|
|
373
|
+
* its bytes change only when a commitment or the date changes, and the
|
|
374
|
+
* provider's prompt cache holds within a day. A line whose text is an
|
|
375
|
+
* instruction is withheld and counted, as every pinned line is.
|
|
376
|
+
*
|
|
377
|
+
* @returns {{ text: string, withheld: number }}
|
|
378
|
+
*/
|
|
379
|
+
export function dueSection(items, { today, zone, workingDays = DUE_WORKING_DAYS }) {
|
|
380
|
+
const open = sortItems(
|
|
381
|
+
(items ?? []).filter((item) => item.state === "open"),
|
|
382
|
+
zone,
|
|
383
|
+
)
|
|
384
|
+
const horizon = workingDaysAfter(today, workingDays)
|
|
385
|
+
let withheld = 0
|
|
386
|
+
const due = []
|
|
387
|
+
for (const item of open) {
|
|
388
|
+
const day = dueDay(item.due, zone)
|
|
389
|
+
if (!day || day > horizon) continue
|
|
390
|
+
if (isInstructionShaped(item.what) || isInstructionShaped(item.owner)) {
|
|
391
|
+
withheld += 1
|
|
392
|
+
continue
|
|
393
|
+
}
|
|
394
|
+
due.push(item)
|
|
395
|
+
}
|
|
396
|
+
if (due.length === 0) return { text: "", withheld }
|
|
397
|
+
const lines = due
|
|
398
|
+
.slice(0, DUE_MAX_LINES)
|
|
399
|
+
.map((item) => `- ${dueLabel(item, today, zone)}: ${shown(item.what, 160)} (${shown(ownerLabel(item.owner), 60)}) [${shown(item.id, 20)}]`)
|
|
400
|
+
const more = open.length - withheld - lines.length
|
|
401
|
+
if (more > 0) lines.push(`(${more} more open: mem_commitments list)`)
|
|
402
|
+
return { text: `## Due (${formatDay(today)})\n${lines.join("\n")}`, withheld }
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Filter a list request: `state` (open by default, or done, cancelled, all),
|
|
407
|
+
* `project`, `owner`, and `due_before` (a day).
|
|
408
|
+
*/
|
|
409
|
+
export function filterItems(items, filter, zone) {
|
|
410
|
+
const state = String(filter?.state ?? "open").toLowerCase()
|
|
411
|
+
const project = String(filter?.project ?? "").trim().toLowerCase()
|
|
412
|
+
const owner = String(filter?.owner ?? "").trim().toLowerCase()
|
|
413
|
+
const before = String(filter?.due_before ?? "").trim()
|
|
414
|
+
return sortItems(
|
|
415
|
+
(items ?? []).filter((item) => {
|
|
416
|
+
if (state !== "all" && item.state !== state) return false
|
|
417
|
+
if (project && item.project !== project) return false
|
|
418
|
+
if (owner && String(item.owner ?? "user").toLowerCase() !== (owner === "me" ? "user" : owner)) return false
|
|
419
|
+
if (before) {
|
|
420
|
+
const day = dueDay(item.due, zone)
|
|
421
|
+
if (!day || day >= before) return false
|
|
422
|
+
}
|
|
423
|
+
return true
|
|
424
|
+
}),
|
|
425
|
+
zone,
|
|
426
|
+
)
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/** One line of a list answer. */
|
|
430
|
+
export function itemLine(item, today, zone) {
|
|
431
|
+
const parts = [`${shown(item.id, 20)}`, shown(item.what, MAX_WHAT_CHARS)]
|
|
432
|
+
const when = item.state === "open" ? dueLabel(item, today, zone) : item.due ? formatDue(item.due, zone) : ""
|
|
433
|
+
if (when) parts.push(item.state === "open" ? when : `due ${when}`)
|
|
434
|
+
if (item.trigger) parts.push(`when: ${shown(item.trigger, MAX_TRIGGER_CHARS)}`)
|
|
435
|
+
parts.push(`owner ${shown(ownerLabel(item.owner), 80)}`)
|
|
436
|
+
if (item.state !== "open") parts.push(`${item.state}${item.closed ? ` ${formatDay(item.closed)}` : ""}`)
|
|
437
|
+
if (item.project) parts.push(`project ${shown(item.project, 80)}`)
|
|
438
|
+
if (item.link) parts.push(`link ${shown(item.link, 200)}`)
|
|
439
|
+
return `- ${parts.join(" · ")}`
|
|
440
|
+
}
|
package/src/runtime.js
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { contextScopeLabel, placementSignature, resolveScope, scopeLabel, taskKey } from "./scope.js"
|
|
2
2
|
import { buildBootstrap } from "./bootstrap.js"
|
|
3
|
+
import { createClock } from "./config.js"
|
|
4
|
+
import { dayIn, dueSection } from "./records.js"
|
|
5
|
+
import { createRecordsStore } from "./records-store.js"
|
|
3
6
|
import { buildCheckpoint, checkpointFingerprint } from "./compaction.js"
|
|
4
7
|
import { credentialLine, unavailableReason } from "./credentials.js"
|
|
5
8
|
import { createControlClient } from "./spaces.js"
|
|
@@ -79,6 +82,10 @@ export function createRuntime(input) {
|
|
|
79
82
|
inflight: null,
|
|
80
83
|
}
|
|
81
84
|
let api = null
|
|
85
|
+
/** The person's clock: real time, or a fixed start for tests and evals. */
|
|
86
|
+
const clock = createClock(config)
|
|
87
|
+
/** Today's date in the agent's zone: part of the pinned block's cache key. */
|
|
88
|
+
const today = () => dayIn(clock.now(), clock.zone)
|
|
82
89
|
const gatewayMode = input.gateway ?? Boolean(config.controlURL)
|
|
83
90
|
const control =
|
|
84
91
|
input.control ??
|
|
@@ -86,6 +93,9 @@ export function createRuntime(input) {
|
|
|
86
93
|
? createControlClient({ controlURL: () => config.controlURL, token: config.token, credentials, log })
|
|
87
94
|
: null)
|
|
88
95
|
|
|
96
|
+
/** The personal space's commitments (the reserved records wiki). */
|
|
97
|
+
const records = createRecordsStore({ backend, control, log })
|
|
98
|
+
|
|
89
99
|
/**
|
|
90
100
|
* One sentence saying why memory is unavailable, or "" when it is. Only a
|
|
91
101
|
* gateway deployment needs a credential and an address; local direct mode
|
|
@@ -339,9 +349,14 @@ export function createRuntime(input) {
|
|
|
339
349
|
return config.agent === "auto" ? "opencode" : String(config.agent)
|
|
340
350
|
}
|
|
341
351
|
|
|
352
|
+
/**
|
|
353
|
+
* The pinned block's identity. The day is part of it because the Due list
|
|
354
|
+
* says "today" and "overdue": the block is rebuilt once when the date
|
|
355
|
+
* changes, and is byte-stable within a day.
|
|
356
|
+
*/
|
|
342
357
|
function cacheKey(sessionID, agent, context) {
|
|
343
358
|
const space = context?.space_id || "local"
|
|
344
|
-
return `${sessionID ?? "global"}::${normaliseAgent(agent)}::${space}::${placementSignature(context)}`
|
|
359
|
+
return `${sessionID ?? "global"}::${normaliseAgent(agent)}::${space}::${placementSignature(context)}::${today()}`
|
|
345
360
|
}
|
|
346
361
|
|
|
347
362
|
function pinKey(sessionID, agent) {
|
|
@@ -363,14 +378,21 @@ export function createRuntime(input) {
|
|
|
363
378
|
(value) => ({ value }),
|
|
364
379
|
(error) => ({ error }),
|
|
365
380
|
)
|
|
366
|
-
const [core, scenarios] = await Promise.all([
|
|
381
|
+
const [core, scenarios, records] = await Promise.all([
|
|
367
382
|
settle(() => backend.readCore({ scope: scoped })),
|
|
368
383
|
settle(() => backend.listScenarios({ scope: scoped })),
|
|
384
|
+
// The person's commitments live in their personal space, also when the
|
|
385
|
+
// session is bound to a shared one. A failed read leaves the Due list
|
|
386
|
+
// out; it never fails the block.
|
|
387
|
+
settle(() => personalRecords(sessionID, agent, context, scoped)),
|
|
369
388
|
])
|
|
370
389
|
if (core.error && scenarios.error) throw core.error
|
|
390
|
+
const day = today()
|
|
391
|
+
const due = records.value ? dueSection(records.value.items, { today: day, zone: clock.zone }) : { text: "", withheld: 0 }
|
|
371
392
|
const block = buildBootstrap({
|
|
372
393
|
core: core.value ?? null,
|
|
373
394
|
scenarios: scenarios.value?.entries ?? [],
|
|
395
|
+
due,
|
|
374
396
|
scope: scoped,
|
|
375
397
|
label: context ? contextScopeLabel(context, scoped) : undefined,
|
|
376
398
|
budgetChars: config.bootstrapChars,
|
|
@@ -378,6 +400,17 @@ export function createRuntime(input) {
|
|
|
378
400
|
return { block, partial: Boolean(core.error || scenarios.error) }
|
|
379
401
|
}
|
|
380
402
|
|
|
403
|
+
/** The personal space's records for the Due list, or null when there are none. */
|
|
404
|
+
async function personalRecords(sessionID, agent, context, scoped) {
|
|
405
|
+
if (!config.tools) return null
|
|
406
|
+
let target = scoped
|
|
407
|
+
if (context && context.space_kind !== "personal") {
|
|
408
|
+
const personal = await captureContext(sessionID, agent, "private")
|
|
409
|
+
target = scopeFor(personal, { sessionID, agent })
|
|
410
|
+
}
|
|
411
|
+
return (await records.read(target)).records
|
|
412
|
+
}
|
|
413
|
+
|
|
381
414
|
/** Fail rather than hang when the control plane is slow. */
|
|
382
415
|
async function bounded(promise, timeoutMs, label) {
|
|
383
416
|
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return promise
|
|
@@ -822,6 +855,9 @@ export function createRuntime(input) {
|
|
|
822
855
|
log,
|
|
823
856
|
backend,
|
|
824
857
|
control,
|
|
858
|
+
clock,
|
|
859
|
+
records,
|
|
860
|
+
today,
|
|
825
861
|
credentials,
|
|
826
862
|
unavailable,
|
|
827
863
|
scope,
|
package/src/skills.js
CHANGED
|
@@ -18,8 +18,9 @@ export async function registerBuiltinSkill(ctx, runtime) {
|
|
|
18
18
|
editor.add({
|
|
19
19
|
id: "mem.usage",
|
|
20
20
|
name: "memory",
|
|
21
|
-
description
|
|
22
|
-
|
|
21
|
+
// The front matter's description is what decides when the skill loads,
|
|
22
|
+
// so the host is given exactly that: one text, no second copy to drift.
|
|
23
|
+
description: frontMatterDescription(content),
|
|
23
24
|
path: BUILTIN_SKILL_PATH,
|
|
24
25
|
content,
|
|
25
26
|
autoinvoke: true,
|
|
@@ -33,6 +34,13 @@ export async function registerBuiltinSkill(ctx, runtime) {
|
|
|
33
34
|
}
|
|
34
35
|
}
|
|
35
36
|
|
|
37
|
+
/** The `description:` line of a skill's YAML front matter. */
|
|
38
|
+
export function frontMatterDescription(content) {
|
|
39
|
+
const block = String(content).match(/^---\r?\n([\s\S]*?)\r?\n---/)
|
|
40
|
+
const line = block?.[1].split(/\r?\n/).find((entry) => entry.startsWith("description:"))
|
|
41
|
+
return line ? line.slice("description:".length).trim() : ""
|
|
42
|
+
}
|
|
43
|
+
|
|
36
44
|
/**
|
|
37
45
|
* Prefix a shared-space skill with its source, after any YAML front matter so
|
|
38
46
|
* the host still parses it.
|