opencode-subagent-tools 0.0.0-stage → 0.1.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/CHANGELOG.md +27 -0
- package/LICENSE +21 -0
- package/README.md +113 -2
- package/SECURITY.md +36 -0
- package/SKILL.md +305 -0
- package/docs/configuration.md +238 -0
- package/docs/development.md +78 -0
- package/docs/installation.md +137 -0
- package/docs/limitations.md +120 -0
- package/docs/reference.md +347 -0
- package/docs/security-model.md +79 -0
- package/package.json +74 -4
- package/src/access.ts +236 -0
- package/src/config.ts +143 -0
- package/src/cursor.ts +112 -0
- package/src/discovery.ts +151 -0
- package/src/errors.ts +18 -0
- package/src/events.ts +190 -0
- package/src/format.ts +34 -0
- package/src/index.ts +116 -0
- package/src/interrupt.ts +20 -0
- package/src/live-state.ts +90 -0
- package/src/messages.ts +196 -0
- package/src/permissions.ts +62 -0
- package/src/session-row.ts +55 -0
- package/src/session.ts +141 -0
- package/src/skill.ts +57 -0
- package/src/status.ts +119 -0
- package/src/text.ts +42 -0
- package/src/tokens.ts +171 -0
- package/src/tools/cancel-descendants.ts +527 -0
- package/src/tools/cancel.ts +205 -0
- package/src/tools/index.ts +39 -0
- package/src/tools/input.ts +73 -0
- package/src/tools/list.ts +502 -0
- package/src/tools/names.ts +11 -0
- package/src/tools/output.ts +169 -0
- package/src/tools/send.ts +335 -0
- package/src/tools/usage.ts +396 -0
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { Plugin } from "@opencode/plugin"
|
|
2
|
+
import {
|
|
3
|
+
MAX_AGENT_NAME_LENGTH,
|
|
4
|
+
MAX_PROMPT_PREVIEW_LENGTH,
|
|
5
|
+
type SessionInfoLike,
|
|
6
|
+
} from "./session"
|
|
7
|
+
import { clip } from "./text"
|
|
8
|
+
import type { ToolCtx } from "./tools/input"
|
|
9
|
+
|
|
10
|
+
export const PERMISSION_ACTION = "subagent.control"
|
|
11
|
+
|
|
12
|
+
export interface GuardTarget {
|
|
13
|
+
id: string
|
|
14
|
+
title?: string
|
|
15
|
+
agent?: string
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const guardTarget = (
|
|
19
|
+
info: SessionInfoLike | undefined,
|
|
20
|
+
sessionID: string,
|
|
21
|
+
): GuardTarget => ({
|
|
22
|
+
id: sessionID,
|
|
23
|
+
title: clip(info?.title, MAX_PROMPT_PREVIEW_LENGTH),
|
|
24
|
+
agent: clip(info?.agent, MAX_AGENT_NAME_LENGTH),
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
export interface GuardDeps {
|
|
28
|
+
permission: Plugin.Context["permission"]
|
|
29
|
+
enabled: boolean
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export const createGuard = ({ permission, enabled }: GuardDeps) => {
|
|
33
|
+
return async (targets: GuardTarget[], context: ToolCtx) => {
|
|
34
|
+
if (!enabled || targets.length === 0) return
|
|
35
|
+
const sessionID = context.sessionID
|
|
36
|
+
if (!sessionID) {
|
|
37
|
+
throw new Error(
|
|
38
|
+
"Refusing: the calling session is unknown, so permissions cannot be checked.",
|
|
39
|
+
)
|
|
40
|
+
}
|
|
41
|
+
await permission.assert({
|
|
42
|
+
sessionID,
|
|
43
|
+
agent: context.agent,
|
|
44
|
+
source:
|
|
45
|
+
context.messageID && context.id
|
|
46
|
+
? { type: "tool" as const, messageID: context.messageID, id: context.id }
|
|
47
|
+
: undefined,
|
|
48
|
+
action: PERMISSION_ACTION,
|
|
49
|
+
resources: targets.map((target) => target.id),
|
|
50
|
+
metadata: {
|
|
51
|
+
count: targets.length,
|
|
52
|
+
targets: targets.map((target) => ({
|
|
53
|
+
id: target.id,
|
|
54
|
+
...(target.title ? { title: target.title } : {}),
|
|
55
|
+
...(target.agent ? { agent: target.agent } : {}),
|
|
56
|
+
})),
|
|
57
|
+
},
|
|
58
|
+
})
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export type Guard = ReturnType<typeof createGuard>
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { LiveStore } from "./live-state"
|
|
2
|
+
import {
|
|
3
|
+
MAX_AGENT_NAME_LENGTH,
|
|
4
|
+
MAX_TITLE_LENGTH,
|
|
5
|
+
normalizeSessionID,
|
|
6
|
+
type SessionInfoLike,
|
|
7
|
+
} from "./session"
|
|
8
|
+
import type { ChildStatus } from "./status"
|
|
9
|
+
import { clip, textLength } from "./text"
|
|
10
|
+
import { normalizeTokens, type TokenUsage } from "./tokens"
|
|
11
|
+
|
|
12
|
+
export interface SessionRow {
|
|
13
|
+
id: string
|
|
14
|
+
parentID?: string
|
|
15
|
+
agent?: string
|
|
16
|
+
title?: string
|
|
17
|
+
titleTruncated?: boolean
|
|
18
|
+
launchedAt: number
|
|
19
|
+
status: ChildStatus
|
|
20
|
+
cost?: number
|
|
21
|
+
tokens?: TokenUsage
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const rowFromInfo = (
|
|
25
|
+
live: LiveStore,
|
|
26
|
+
info: SessionInfoLike,
|
|
27
|
+
fallback?: SessionRow,
|
|
28
|
+
): SessionRow | undefined => {
|
|
29
|
+
const id = normalizeSessionID(info.id) ?? fallback?.id
|
|
30
|
+
if (!id) return undefined
|
|
31
|
+
const created = info.time?.created
|
|
32
|
+
const updated = info.time?.updated
|
|
33
|
+
const launchedAt =
|
|
34
|
+
typeof created === "number" && Number.isFinite(created)
|
|
35
|
+
? created
|
|
36
|
+
: (fallback?.launchedAt ??
|
|
37
|
+
(typeof updated === "number" && Number.isFinite(updated) ? updated : 0))
|
|
38
|
+
return {
|
|
39
|
+
id,
|
|
40
|
+
parentID: normalizeSessionID(info.parentID) ?? fallback?.parentID,
|
|
41
|
+
agent: clip(info.agent, MAX_AGENT_NAME_LENGTH) ?? fallback?.agent,
|
|
42
|
+
title: clip(info.title, MAX_TITLE_LENGTH) ?? fallback?.title,
|
|
43
|
+
titleTruncated:
|
|
44
|
+
typeof info.title === "string"
|
|
45
|
+
? textLength(info.title) > MAX_TITLE_LENGTH
|
|
46
|
+
: fallback?.titleTruncated,
|
|
47
|
+
launchedAt,
|
|
48
|
+
status: live.statusFor(info, id),
|
|
49
|
+
cost:
|
|
50
|
+
typeof info.cost === "number" && Number.isFinite(info.cost)
|
|
51
|
+
? info.cost
|
|
52
|
+
: fallback?.cost,
|
|
53
|
+
tokens: normalizeTokens(info.tokens) ?? fallback?.tokens,
|
|
54
|
+
}
|
|
55
|
+
}
|
package/src/session.ts
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { hasUnsafeIdCharacters } from "./text"
|
|
2
|
+
|
|
3
|
+
export const MAX_SESSION_ID_LENGTH = 80
|
|
4
|
+
export const MAX_AGENT_NAME_LENGTH = 80
|
|
5
|
+
export const MAX_TITLE_LENGTH = 200
|
|
6
|
+
export const MAX_PROMPT_PREVIEW_LENGTH = 60
|
|
7
|
+
|
|
8
|
+
export interface RequestOptions {
|
|
9
|
+
signal?: AbortSignal
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface TokenUsageLike {
|
|
13
|
+
input?: unknown
|
|
14
|
+
output?: unknown
|
|
15
|
+
reasoning?: unknown
|
|
16
|
+
cache?: { read?: unknown; write?: unknown }
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface ModelRefLike {
|
|
20
|
+
id?: string
|
|
21
|
+
providerID?: string
|
|
22
|
+
variant?: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface ModelInfoLike {
|
|
26
|
+
id?: string
|
|
27
|
+
modelID?: string
|
|
28
|
+
providerID?: string
|
|
29
|
+
limit?: { context?: number }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface SessionInfoLike {
|
|
33
|
+
id?: string
|
|
34
|
+
parentID?: string
|
|
35
|
+
agent?: string
|
|
36
|
+
title?: string
|
|
37
|
+
outcome?: string
|
|
38
|
+
model?: ModelRefLike
|
|
39
|
+
cost?: number
|
|
40
|
+
tokens?: TokenUsageLike
|
|
41
|
+
revert?: { messageID?: string }
|
|
42
|
+
time?: {
|
|
43
|
+
created?: number
|
|
44
|
+
updated?: number
|
|
45
|
+
busy?: number
|
|
46
|
+
idle?: number
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Normalize a model- or server-provided session ID without silently truncating it. */
|
|
51
|
+
export const normalizeSessionID = (value: unknown): string | undefined => {
|
|
52
|
+
if (typeof value !== "string") return undefined
|
|
53
|
+
const id = value.trim()
|
|
54
|
+
if (id.length === 0 || id.length > MAX_SESSION_ID_LENGTH || hasUnsafeIdCharacters(id)) {
|
|
55
|
+
return undefined
|
|
56
|
+
}
|
|
57
|
+
return id
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export const MESSAGE_TYPE = {
|
|
61
|
+
assistant: "assistant",
|
|
62
|
+
compaction: "compaction",
|
|
63
|
+
} as const
|
|
64
|
+
|
|
65
|
+
export const MESSAGE_STATUS = {
|
|
66
|
+
completed: "completed",
|
|
67
|
+
} as const
|
|
68
|
+
|
|
69
|
+
export interface UsageMessage {
|
|
70
|
+
id?: string
|
|
71
|
+
type?: string
|
|
72
|
+
status?: string
|
|
73
|
+
tokens?: TokenUsageLike
|
|
74
|
+
model?: ModelRefLike
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface SessionListPage {
|
|
78
|
+
data?: SessionInfoLike[]
|
|
79
|
+
cursor?: { next?: string | null }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export type SessionListResult = SessionListPage | SessionInfoLike[]
|
|
83
|
+
|
|
84
|
+
export type SessionList = (
|
|
85
|
+
input: {
|
|
86
|
+
parentID?: string
|
|
87
|
+
limit?: number
|
|
88
|
+
order?: "asc" | "desc"
|
|
89
|
+
archived?: boolean
|
|
90
|
+
cursor?: string
|
|
91
|
+
},
|
|
92
|
+
options?: RequestOptions,
|
|
93
|
+
) => Promise<SessionListResult | undefined>
|
|
94
|
+
|
|
95
|
+
const isSessionInfoLike = (value: unknown): value is SessionInfoLike =>
|
|
96
|
+
Boolean(value) &&
|
|
97
|
+
typeof value === "object" &&
|
|
98
|
+
typeof (value as SessionInfoLike).id === "string" &&
|
|
99
|
+
(value as SessionInfoLike).id!.length > 0
|
|
100
|
+
|
|
101
|
+
export interface SessionListPageResult {
|
|
102
|
+
items: SessionInfoLike[]
|
|
103
|
+
cursor?: string
|
|
104
|
+
/** False when the response or one of its items was malformed. */
|
|
105
|
+
valid: boolean
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Accept both the current `{ data, cursor }` response and a bare array.
|
|
110
|
+
* A malformed response is reported as invalid instead of looking like a
|
|
111
|
+
* complete empty page.
|
|
112
|
+
*/
|
|
113
|
+
export const readSessionListPage = (
|
|
114
|
+
value: SessionListResult | undefined,
|
|
115
|
+
): SessionListPageResult => {
|
|
116
|
+
if (Array.isArray(value)) {
|
|
117
|
+
const items = value.filter(isSessionInfoLike)
|
|
118
|
+
return { items, valid: items.length === value.length }
|
|
119
|
+
}
|
|
120
|
+
if (!value || typeof value !== "object" || !Array.isArray(value.data)) {
|
|
121
|
+
return { items: [], valid: false }
|
|
122
|
+
}
|
|
123
|
+
const items = value.data.filter(isSessionInfoLike)
|
|
124
|
+
const cursorValue: unknown = value.cursor
|
|
125
|
+
let cursor: string | undefined
|
|
126
|
+
let cursorValid = true
|
|
127
|
+
if (cursorValue !== undefined && cursorValue !== null) {
|
|
128
|
+
if (typeof cursorValue !== "object" || Array.isArray(cursorValue)) {
|
|
129
|
+
cursorValid = false
|
|
130
|
+
} else {
|
|
131
|
+
const next = (cursorValue as { next?: unknown }).next
|
|
132
|
+
if (typeof next === "string" && next.length > 0) cursor = next
|
|
133
|
+
else if (next !== undefined && next !== null) cursorValid = false
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return {
|
|
137
|
+
items,
|
|
138
|
+
cursor,
|
|
139
|
+
valid: items.length === value.data.length && cursorValid,
|
|
140
|
+
}
|
|
141
|
+
}
|
package/src/skill.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises"
|
|
2
|
+
import { fileURLToPath } from "node:url"
|
|
3
|
+
import { Skill, type Plugin } from "@opencode/plugin"
|
|
4
|
+
|
|
5
|
+
export const SKILL_ID = "subagent-tools"
|
|
6
|
+
export const SKILL_NAME = "Subagent Tools"
|
|
7
|
+
export const SKILL_DESCRIPTION =
|
|
8
|
+
"Use the subagent tools to list, steer, queue, cancel, and inject context into OpenCode subagents. " +
|
|
9
|
+
"Covers delivery modes, soft interrupts, read-back lag, parent wake, nested depth, and permissions."
|
|
10
|
+
export const SKILL_PATH = fileURLToPath(new URL("../SKILL.md", import.meta.url))
|
|
11
|
+
|
|
12
|
+
/** Read the name/description from a SKILL.md frontmatter block and return the body. */
|
|
13
|
+
export const parseSkillFile = (
|
|
14
|
+
text: string,
|
|
15
|
+
): { name?: string; description?: string; content: string } => {
|
|
16
|
+
const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text)
|
|
17
|
+
if (!match) return { content: text }
|
|
18
|
+
const meta = new Map<string, string>()
|
|
19
|
+
for (const line of match[1].split(/\r?\n/)) {
|
|
20
|
+
const separator = line.indexOf(":")
|
|
21
|
+
if (separator <= 0) continue
|
|
22
|
+
const key = line.slice(0, separator).trim()
|
|
23
|
+
const value = line
|
|
24
|
+
.slice(separator + 1)
|
|
25
|
+
.trim()
|
|
26
|
+
.replace(/^["']|["']$/g, "")
|
|
27
|
+
if (key && value) meta.set(key, value)
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
name: meta.get("name"),
|
|
31
|
+
description: meta.get("description"),
|
|
32
|
+
content: text.slice(match[0].length),
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Register the bundled SKILL.md as a model-facing skill. The tools remain the
|
|
38
|
+
* source of truth; a missing skill file only skips the optional guide.
|
|
39
|
+
*/
|
|
40
|
+
export const registerSkill = async (skill: Plugin.Context["skill"]) => {
|
|
41
|
+
try {
|
|
42
|
+
const skillText = await readFile(SKILL_PATH, "utf8")
|
|
43
|
+
const parsed = parseSkillFile(skillText)
|
|
44
|
+
return await skill.transform((editor) => {
|
|
45
|
+
editor.add({
|
|
46
|
+
id: Skill.ID.make(SKILL_ID),
|
|
47
|
+
name: Skill.Name.make(parsed.name ?? SKILL_NAME),
|
|
48
|
+
description: parsed.description ?? SKILL_DESCRIPTION,
|
|
49
|
+
path: Skill.Info.fields.path.make(SKILL_PATH),
|
|
50
|
+
content: parsed.content,
|
|
51
|
+
})
|
|
52
|
+
})
|
|
53
|
+
} catch (error) {
|
|
54
|
+
console.error("subagent-tools: failed to register SKILL.md", error)
|
|
55
|
+
return undefined
|
|
56
|
+
}
|
|
57
|
+
}
|
package/src/status.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import type { SessionInfoLike } from "./session"
|
|
2
|
+
|
|
3
|
+
export const STATUS = {
|
|
4
|
+
running: "running",
|
|
5
|
+
stopped: "stopped",
|
|
6
|
+
failed: "failed",
|
|
7
|
+
finished: "finished",
|
|
8
|
+
unknown: "unknown",
|
|
9
|
+
} as const
|
|
10
|
+
|
|
11
|
+
export type ChildStatus = (typeof STATUS)[keyof typeof STATUS]
|
|
12
|
+
|
|
13
|
+
export const OUTCOME = {
|
|
14
|
+
interrupted: "interrupted",
|
|
15
|
+
failed: "failed",
|
|
16
|
+
succeeded: "succeeded",
|
|
17
|
+
} as const
|
|
18
|
+
|
|
19
|
+
export type Outcome = (typeof OUTCOME)[keyof typeof OUTCOME]
|
|
20
|
+
|
|
21
|
+
export const CHILD_STATUSES: readonly ChildStatus[] = Object.values(STATUS)
|
|
22
|
+
const CHILD_STATUS_SET: ReadonlySet<string> = new Set(CHILD_STATUSES)
|
|
23
|
+
|
|
24
|
+
export const isChildStatus = (value: string): value is ChildStatus =>
|
|
25
|
+
CHILD_STATUS_SET.has(value)
|
|
26
|
+
|
|
27
|
+
export interface StatusMeta {
|
|
28
|
+
/** The run is over; no further step is expected without a resume. */
|
|
29
|
+
terminal: boolean
|
|
30
|
+
/** Persisted usage may lag because the session is active or unresolved. */
|
|
31
|
+
usageMayLag: boolean
|
|
32
|
+
/** Safe to treat a message with `resume: false` as pending. */
|
|
33
|
+
idle: boolean
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export const STATUS_META: Readonly<Record<ChildStatus, StatusMeta>> = {
|
|
37
|
+
[STATUS.running]: { terminal: false, usageMayLag: true, idle: false },
|
|
38
|
+
[STATUS.stopped]: { terminal: true, usageMayLag: false, idle: true },
|
|
39
|
+
[STATUS.failed]: { terminal: true, usageMayLag: false, idle: true },
|
|
40
|
+
[STATUS.finished]: { terminal: true, usageMayLag: false, idle: true },
|
|
41
|
+
// `unknown` may still be running, so it is neither terminal nor idle.
|
|
42
|
+
[STATUS.unknown]: { terminal: false, usageMayLag: true, idle: false },
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const STATUS_META_MAP: ReadonlyMap<ChildStatus, StatusMeta> = new Map(
|
|
46
|
+
Object.entries(STATUS_META) as Array<[ChildStatus, StatusMeta]>,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
export const statusMeta = (status: ChildStatus): StatusMeta =>
|
|
50
|
+
STATUS_META_MAP.get(status) ?? STATUS_META[STATUS.unknown]
|
|
51
|
+
|
|
52
|
+
export const statusUsageMayLag = (status: ChildStatus): boolean =>
|
|
53
|
+
statusMeta(status).usageMayLag
|
|
54
|
+
|
|
55
|
+
export const statusIsIdle = (status: ChildStatus | undefined): boolean =>
|
|
56
|
+
status !== undefined && statusMeta(status).idle
|
|
57
|
+
|
|
58
|
+
export const TERMINAL_STATUSES: ReadonlySet<ChildStatus> = new Set(
|
|
59
|
+
CHILD_STATUSES.filter((status) => statusMeta(status).terminal),
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
export const OUTCOMES: readonly Outcome[] = Object.values(OUTCOME)
|
|
63
|
+
const OUTCOME_SET: ReadonlySet<string> = new Set(OUTCOMES)
|
|
64
|
+
|
|
65
|
+
export const isOutcome = (value: unknown): value is Outcome =>
|
|
66
|
+
typeof value === "string" && OUTCOME_SET.has(value)
|
|
67
|
+
|
|
68
|
+
export const OUTCOME_STATUS: Readonly<Record<Outcome, ChildStatus>> = {
|
|
69
|
+
[OUTCOME.interrupted]: STATUS.stopped,
|
|
70
|
+
[OUTCOME.failed]: STATUS.failed,
|
|
71
|
+
[OUTCOME.succeeded]: STATUS.finished,
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const OUTCOME_STATUS_MAP: ReadonlyMap<Outcome, ChildStatus> = new Map(
|
|
75
|
+
Object.entries(OUTCOME_STATUS) as Array<[Outcome, ChildStatus]>,
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
const statusFromOutcome = (outcome: unknown): ChildStatus | undefined => {
|
|
79
|
+
if (outcome === undefined) return undefined
|
|
80
|
+
if (!isOutcome(outcome)) return STATUS.unknown
|
|
81
|
+
return OUTCOME_STATUS_MAP.get(outcome)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export const SESSION_STATUS = {
|
|
85
|
+
busy: "busy",
|
|
86
|
+
retry: "retry",
|
|
87
|
+
idle: "idle",
|
|
88
|
+
} as const
|
|
89
|
+
|
|
90
|
+
export const BUSY_SESSION_STATUSES: ReadonlySet<string> = new Set([
|
|
91
|
+
SESSION_STATUS.busy,
|
|
92
|
+
SESSION_STATUS.retry,
|
|
93
|
+
])
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Derive a state from a session record. `busy`/`idle` describe the current
|
|
97
|
+
* execution; `outcome` describes the last completed one. A resumed child can be
|
|
98
|
+
* running while its outcome is still the previous run's.
|
|
99
|
+
*/
|
|
100
|
+
export const statusFromSession = (info: SessionInfoLike): ChildStatus | undefined => {
|
|
101
|
+
const idle = info.time?.idle
|
|
102
|
+
const busy = info.time?.busy
|
|
103
|
+
const outcomeStatus = statusFromOutcome(info.outcome)
|
|
104
|
+
|
|
105
|
+
// A terminal outcome is recorded at `time.idle`. Without that marker, the
|
|
106
|
+
// outcome is the most reliable evidence we have.
|
|
107
|
+
if (idle === undefined) {
|
|
108
|
+
if (outcomeStatus) return outcomeStatus
|
|
109
|
+
return typeof busy === "number" ? STATUS.running : undefined
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// `busy`/`idle` describe the current execution; `outcome` describes the last
|
|
113
|
+
// completed one. A resumed child can have a stale outcome while busy > idle.
|
|
114
|
+
if (typeof busy === "number" && busy > idle) return STATUS.running
|
|
115
|
+
if (outcomeStatus) return outcomeStatus
|
|
116
|
+
// An unrecognised outcome stays `unknown` instead of falling back to a
|
|
117
|
+
// timestamp heuristic that may claim the session is running.
|
|
118
|
+
return (info.time?.updated ?? 0) > idle ? STATUS.running : undefined
|
|
119
|
+
}
|
package/src/text.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** Truncate a string to a maximum number of Unicode code points. */
|
|
2
|
+
export const clip = (value: unknown, max: number): string | undefined => {
|
|
3
|
+
if (typeof value !== "string" || value.length === 0) return undefined
|
|
4
|
+
const chars = Array.from(value)
|
|
5
|
+
return chars.length > max ? chars.slice(0, max).join("") : value
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** Clip a model-provided string, trimming surrounding whitespace and rejecting blank input. */
|
|
9
|
+
export const clipText = (value: unknown, max: number): string | undefined => {
|
|
10
|
+
const text = clip(value, max)?.trim()
|
|
11
|
+
return text && text.length > 0 ? text : undefined
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Count characters by Unicode code point, matching JSON Schema maxLength. */
|
|
15
|
+
export const textLength = (value: string): number => Array.from(value).length
|
|
16
|
+
|
|
17
|
+
/** C0/C1 controls, DEL, and Unicode line/paragraph separators. */
|
|
18
|
+
export const isUnsafeControlCode = (code: number): boolean =>
|
|
19
|
+
code < 0x20 || (code >= 0x7f && code <= 0x9f) || code === 0x2028 || code === 0x2029
|
|
20
|
+
|
|
21
|
+
/** Reject spaces and control characters in identifiers. */
|
|
22
|
+
export const hasUnsafeIdCharacters = (value: string): boolean =>
|
|
23
|
+
Array.from(value).some((char) => {
|
|
24
|
+
const code = char.codePointAt(0) ?? 0
|
|
25
|
+
return code <= 0x20 || isUnsafeControlCode(code)
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Reject over-long input with a short message instead of letting the tool
|
|
30
|
+
* runtime echo the whole argument back in a schema-validation error.
|
|
31
|
+
*/
|
|
32
|
+
export const maxLengthError = (
|
|
33
|
+
value: unknown,
|
|
34
|
+
max: number,
|
|
35
|
+
field: string,
|
|
36
|
+
): string | undefined => {
|
|
37
|
+
if (typeof value !== "string") return undefined
|
|
38
|
+
const length = textLength(value)
|
|
39
|
+
return length > max
|
|
40
|
+
? `${field} is ${length} characters; maximum is ${max}. Shorten it and retry.`
|
|
41
|
+
: undefined
|
|
42
|
+
}
|
package/src/tokens.ts
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import {
|
|
2
|
+
MESSAGE_STATUS,
|
|
3
|
+
MESSAGE_TYPE,
|
|
4
|
+
type ModelRefLike,
|
|
5
|
+
type TokenUsageLike,
|
|
6
|
+
type UsageMessage,
|
|
7
|
+
} from "./session"
|
|
8
|
+
|
|
9
|
+
export interface TokenUsage {
|
|
10
|
+
input: number
|
|
11
|
+
output: number
|
|
12
|
+
reasoning: number
|
|
13
|
+
cache: { read: number; write: number }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface LastRequestUsage {
|
|
17
|
+
input: number
|
|
18
|
+
output: number
|
|
19
|
+
reasoning: number
|
|
20
|
+
cacheRead: number
|
|
21
|
+
cacheWrite: number
|
|
22
|
+
total: number
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const isNumber = (value: unknown): value is number =>
|
|
26
|
+
typeof value === "number" && Number.isFinite(value)
|
|
27
|
+
|
|
28
|
+
export const normalizeTokens = (value: unknown): TokenUsage | undefined => {
|
|
29
|
+
if (!value || typeof value !== "object") return undefined
|
|
30
|
+
const tokens = value as TokenUsageLike
|
|
31
|
+
const input = isNumber(tokens.input) ? tokens.input : undefined
|
|
32
|
+
const output = isNumber(tokens.output) ? tokens.output : undefined
|
|
33
|
+
const reasoning = isNumber(tokens.reasoning) ? tokens.reasoning : undefined
|
|
34
|
+
const cacheRead = isNumber(tokens.cache?.read) ? tokens.cache.read : undefined
|
|
35
|
+
const cacheWrite = isNumber(tokens.cache?.write) ? tokens.cache.write : undefined
|
|
36
|
+
|
|
37
|
+
// An object with no numeric token fields is missing data, not zero usage.
|
|
38
|
+
if (
|
|
39
|
+
input === undefined &&
|
|
40
|
+
output === undefined &&
|
|
41
|
+
reasoning === undefined &&
|
|
42
|
+
cacheRead === undefined &&
|
|
43
|
+
cacheWrite === undefined
|
|
44
|
+
) {
|
|
45
|
+
return undefined
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return {
|
|
49
|
+
input: input ?? 0,
|
|
50
|
+
output: output ?? 0,
|
|
51
|
+
reasoning: reasoning ?? 0,
|
|
52
|
+
cache: {
|
|
53
|
+
read: cacheRead ?? 0,
|
|
54
|
+
write: cacheWrite ?? 0,
|
|
55
|
+
},
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export const tokensUsed = (tokens: TokenUsage): number =>
|
|
60
|
+
tokens.input + tokens.output + tokens.reasoning
|
|
61
|
+
|
|
62
|
+
export const tokensTotal = (tokens: TokenUsage): number =>
|
|
63
|
+
tokensUsed(tokens) + tokens.cache.read + tokens.cache.write
|
|
64
|
+
|
|
65
|
+
export const addTokens = (
|
|
66
|
+
left?: TokenUsage,
|
|
67
|
+
right?: TokenUsage,
|
|
68
|
+
): TokenUsage | undefined => {
|
|
69
|
+
if (!left) return right
|
|
70
|
+
if (!right) return left
|
|
71
|
+
return {
|
|
72
|
+
input: left.input + right.input,
|
|
73
|
+
output: left.output + right.output,
|
|
74
|
+
reasoning: left.reasoning + right.reasoning,
|
|
75
|
+
cache: {
|
|
76
|
+
read: left.cache.read + right.cache.read,
|
|
77
|
+
write: left.cache.write + right.cache.write,
|
|
78
|
+
},
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export const CONTEXT_USAGE = {
|
|
83
|
+
usage: "usage",
|
|
84
|
+
empty: "empty",
|
|
85
|
+
missing: "missing",
|
|
86
|
+
} as const
|
|
87
|
+
|
|
88
|
+
export type ContextUsage =
|
|
89
|
+
| {
|
|
90
|
+
kind: typeof CONTEXT_USAGE.usage
|
|
91
|
+
total: number
|
|
92
|
+
lastRequest: LastRequestUsage
|
|
93
|
+
model?: ModelRefLike
|
|
94
|
+
}
|
|
95
|
+
| { kind: typeof CONTEXT_USAGE.empty }
|
|
96
|
+
| { kind: typeof CONTEXT_USAGE.missing }
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Reproduce the UI's context number: the last assistant step after the last
|
|
100
|
+
* completed compaction and before the staged-revert boundary. All five token
|
|
101
|
+
* fields are included, matching the OpenCode UI.
|
|
102
|
+
*
|
|
103
|
+
* `empty` means there is no assistant step after compaction; `missing` means
|
|
104
|
+
* the step exists but its token data is unavailable. The two are not the same
|
|
105
|
+
* as a real zero.
|
|
106
|
+
*/
|
|
107
|
+
export const contextFromMessages = (
|
|
108
|
+
messages: readonly UsageMessage[],
|
|
109
|
+
revertMessageID?: string,
|
|
110
|
+
): ContextUsage | undefined => {
|
|
111
|
+
let end = messages.length
|
|
112
|
+
if (revertMessageID) {
|
|
113
|
+
const boundary = messages.findIndex((message) => message?.id === revertMessageID)
|
|
114
|
+
if (boundary === -1) return undefined
|
|
115
|
+
end = boundary
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
let compactionIndex = -1
|
|
119
|
+
for (let index = end - 1; index >= 0; index--) {
|
|
120
|
+
const message = messages[index]
|
|
121
|
+
if (!message) continue
|
|
122
|
+
if (
|
|
123
|
+
message.type === MESSAGE_TYPE.compaction &&
|
|
124
|
+
message.status === MESSAGE_STATUS.completed
|
|
125
|
+
) {
|
|
126
|
+
compactionIndex = index
|
|
127
|
+
break
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
for (let index = end - 1; index > compactionIndex; index--) {
|
|
132
|
+
const message = messages[index]
|
|
133
|
+
if (!message || message.type !== MESSAGE_TYPE.assistant) continue
|
|
134
|
+
const tokens = normalizeTokens(message.tokens)
|
|
135
|
+
if (!tokens) return { kind: CONTEXT_USAGE.missing }
|
|
136
|
+
return {
|
|
137
|
+
kind: CONTEXT_USAGE.usage,
|
|
138
|
+
total: tokensTotal(tokens),
|
|
139
|
+
lastRequest: {
|
|
140
|
+
input: tokens.input,
|
|
141
|
+
output: tokens.output,
|
|
142
|
+
reasoning: tokens.reasoning,
|
|
143
|
+
cacheRead: tokens.cache.read,
|
|
144
|
+
cacheWrite: tokens.cache.write,
|
|
145
|
+
total: tokensTotal(tokens),
|
|
146
|
+
},
|
|
147
|
+
model: message.model,
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return { kind: CONTEXT_USAGE.empty }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export const TOKEN_USAGE_SCHEMA = {
|
|
154
|
+
type: "object",
|
|
155
|
+
properties: {
|
|
156
|
+
input: { type: "integer" },
|
|
157
|
+
output: { type: "integer" },
|
|
158
|
+
reasoning: { type: "integer" },
|
|
159
|
+
cache: {
|
|
160
|
+
type: "object",
|
|
161
|
+
properties: {
|
|
162
|
+
read: { type: "integer" },
|
|
163
|
+
write: { type: "integer" },
|
|
164
|
+
},
|
|
165
|
+
required: ["read", "write"],
|
|
166
|
+
additionalProperties: false,
|
|
167
|
+
},
|
|
168
|
+
},
|
|
169
|
+
required: ["input", "output", "reasoning", "cache"],
|
|
170
|
+
additionalProperties: false,
|
|
171
|
+
} as const
|