@lincyaw/mcp 0.0.0-stage → 1.0.0-rc.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/LICENSE +202 -0
- package/README.md +22 -2
- package/bin/presmium-mcp.mjs +15 -0
- package/package.json +41 -3
- package/src/client.ts +77 -0
- package/src/deck.ts +212 -0
- package/src/focus.ts +87 -0
- package/src/host.ts +73 -0
- package/src/index.ts +4 -0
- package/src/mcp.ts +560 -0
- package/src/messages.ts +35 -0
- package/src/stdio.ts +101 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,23 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @lincyaw/mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Presmium's agent environment: a document's tools and resources over MCP, for agents such as Claude Code, Codex or VS Code.
|
|
4
|
+
|
|
5
|
+
Part of [Presmium](https://github.com/Lincyaw/presmium), which turns lectures written in MyST Markdown into web pages, slides, Jupyter notebooks and narrated lectures.
|
|
6
|
+
|
|
7
|
+
## Usage
|
|
8
|
+
|
|
9
|
+
`presmium dev` and `presmium serve` serve it at `/mcp` and print its address and the file that holds its token. Without a server, run it over stdio:
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
pnpm exec presmium-mcp <document directory>
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
The reading tools (`list_sections`, `get_section`, `get_step`, `search`, `get_code_ref`, `get_outputs`, `get_diagnostics`, `locate_source` and others) are always there; `--allow operate` also provides `run_code` and `build`.
|
|
16
|
+
|
|
17
|
+
## Documentation
|
|
18
|
+
|
|
19
|
+
- [Author guide](https://github.com/Lincyaw/presmium/blob/main/site/guide/lecture.en.md): agents in your editor
|
|
20
|
+
|
|
21
|
+
## License
|
|
22
|
+
|
|
23
|
+
Apache-2.0
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createJiti } from 'jiti'
|
|
3
|
+
|
|
4
|
+
console.log = console.info = console.debug = console.error
|
|
5
|
+
|
|
6
|
+
const emitWarning = process.emitWarning
|
|
7
|
+
process.emitWarning = (warning, ...args) => {
|
|
8
|
+
const code = typeof args[0] === 'object' ? args[0]?.code : args[1]
|
|
9
|
+
if (code !== 'DEP0040') emitWarning.call(process, warning, ...args)
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const jiti = createJiti(import.meta.url)
|
|
13
|
+
const { main } = await jiti.import('../src/stdio.ts')
|
|
14
|
+
const code = await main(process.argv.slice(2))
|
|
15
|
+
if (code !== undefined) process.exitCode = code
|
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lincyaw/mcp",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0-rc.0",
|
|
4
|
+
"description": "Presmium's agent environment: a document's tools and resources over MCP, and presmium-mcp over stdio",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/Lincyaw/presmium.git",
|
|
9
|
+
"directory": "packages/mcp"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/Lincyaw/presmium/tree/main/packages/mcp#readme",
|
|
12
|
+
"bugs": "https://github.com/Lincyaw/presmium/issues",
|
|
13
|
+
"keywords": [
|
|
14
|
+
"presmium",
|
|
15
|
+
"mcp",
|
|
16
|
+
"agent"
|
|
17
|
+
],
|
|
18
|
+
"type": "module",
|
|
19
|
+
"engines": {
|
|
20
|
+
"node": ">=22.19"
|
|
21
|
+
},
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public"
|
|
24
|
+
},
|
|
25
|
+
"bin": {
|
|
26
|
+
"presmium-mcp": "./bin/presmium-mcp.mjs"
|
|
27
|
+
},
|
|
28
|
+
"exports": {
|
|
29
|
+
".": "./src/index.ts",
|
|
30
|
+
"./client": "./src/client.ts"
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"bin",
|
|
34
|
+
"src"
|
|
35
|
+
],
|
|
36
|
+
"dependencies": {
|
|
37
|
+
"@modelcontextprotocol/client": "2.3.1",
|
|
38
|
+
"@modelcontextprotocol/server": "2.3.1",
|
|
39
|
+
"jiti": "^2.7.0",
|
|
40
|
+
"minisearch": "7.2.0",
|
|
41
|
+
"@lincyaw/compiler": "1.0.0-rc.0",
|
|
42
|
+
"@lincyaw/kernel": "1.0.0-rc.0"
|
|
43
|
+
}
|
|
6
44
|
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client'
|
|
2
|
+
import { deckLocale, isRecord } from '@lincyaw/kernel'
|
|
3
|
+
import type { ApprovalKind } from '@lincyaw/kernel'
|
|
4
|
+
import { MCP_MESSAGES } from './messages.ts'
|
|
5
|
+
|
|
6
|
+
export interface ListedTool {
|
|
7
|
+
name: string
|
|
8
|
+
description: string
|
|
9
|
+
inputSchema: Record<string, unknown>
|
|
10
|
+
kind: 'read' | ApprovalKind
|
|
11
|
+
approval?: 'ask' | 'allow'
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface CalledTool {
|
|
15
|
+
isError: boolean
|
|
16
|
+
text: string
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface PresmiumMcpClient {
|
|
20
|
+
tools(): Promise<ListedTool[]>
|
|
21
|
+
call(name: string, args: Record<string, unknown>, signal?: AbortSignal): Promise<CalledTool>
|
|
22
|
+
read(uri: string): Promise<unknown>
|
|
23
|
+
close(): Promise<void>
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const KINDS = new Set(['read', 'operate', 'spend', 'write', 'agent'])
|
|
27
|
+
const CALL_TIMEOUT_MS = 10 * 60_000
|
|
28
|
+
|
|
29
|
+
export async function connectPresmiumMcp(url: string, token: string, name = 'presmium-dsh'): Promise<PresmiumMcpClient> {
|
|
30
|
+
const client = new Client({ name, version: '0.1.0' }, { versionNegotiation: { mode: 'auto' } })
|
|
31
|
+
await client.connect(new StreamableHTTPClientTransport(new URL(url), { requestInit: { headers: { Authorization: `Bearer ${token}` } } }))
|
|
32
|
+
return {
|
|
33
|
+
async tools() {
|
|
34
|
+
const listed: ListedTool[] = []
|
|
35
|
+
let cursor: string | undefined
|
|
36
|
+
do {
|
|
37
|
+
const page = await client.listTools(cursor ? { cursor } : undefined)
|
|
38
|
+
for (const tool of page.tools) {
|
|
39
|
+
const meta = isRecord(tool._meta) ? tool._meta : {}
|
|
40
|
+
const kind = typeof meta['presmium/kind'] === 'string' && KINDS.has(meta['presmium/kind']) ? meta['presmium/kind'] as ListedTool['kind'] : (tool.annotations?.readOnlyHint ? 'read' : 'operate')
|
|
41
|
+
const approval = meta['presmium/approval'] === 'allow' ? 'allow' : meta['presmium/approval'] === 'ask' ? 'ask' : undefined
|
|
42
|
+
listed.push({ name: tool.name, description: tool.description ?? tool.name, inputSchema: tool.inputSchema as Record<string, unknown>, kind, ...approval ? { approval } : {} })
|
|
43
|
+
}
|
|
44
|
+
cursor = page.nextCursor
|
|
45
|
+
} while (cursor)
|
|
46
|
+
return listed
|
|
47
|
+
},
|
|
48
|
+
async call(tool, args, signal) {
|
|
49
|
+
const result = await client.callTool({ name: tool, arguments: args }, { signal, timeout: CALL_TIMEOUT_MS })
|
|
50
|
+
const content = Array.isArray(result.content) ? result.content as { type: string, text?: string }[] : []
|
|
51
|
+
return { isError: result.isError === true, text: content.map(part => part.text ?? '').join('\n') }
|
|
52
|
+
},
|
|
53
|
+
async read(uri) {
|
|
54
|
+
const { contents } = await client.readResource({ uri })
|
|
55
|
+
const text = (contents[0] as { text?: string } | undefined)?.text ?? ''
|
|
56
|
+
try {
|
|
57
|
+
return JSON.parse(text) as unknown
|
|
58
|
+
} catch {
|
|
59
|
+
return text
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
close: () => client.close(),
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function describeOperation(tool: string, args: Record<string, unknown>, lang?: string): string {
|
|
67
|
+
const m = MCP_MESSAGES[deckLocale(lang)]
|
|
68
|
+
const text = (value: unknown) => (typeof value === 'string' ? value : typeof value === 'number' ? String(value) : '')
|
|
69
|
+
switch (tool) {
|
|
70
|
+
case 'navigate': return m.navigate(text(args.section), typeof args.step === 'number' ? args.step : 0)
|
|
71
|
+
case 'run_code': return m.run(text(args.section), text(args.block))
|
|
72
|
+
case 'build': return m.build(Array.isArray(args.to) && args.to.length ? args.to.join(', ') : m.allRenderers)
|
|
73
|
+
case 'classroom_start': return m.classroomStart(text(args.name))
|
|
74
|
+
case 'classroom_end': return m.classroomEnd
|
|
75
|
+
default: return m.tool(tool)
|
|
76
|
+
}
|
|
77
|
+
}
|
package/src/deck.ts
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { dirname, relative } from 'node:path'
|
|
2
|
+
import { blockState, blockText, blockVisible, chapters, irBlocks, narrationAt, tokenize } from '@lincyaw/kernel'
|
|
3
|
+
import type { CodeNode, Finding, IRBlock, IRDocument, IRSection, RecordedRun, RunOutput, RunResult, SourcePos } from '@lincyaw/kernel'
|
|
4
|
+
import MiniSearch from 'minisearch'
|
|
5
|
+
|
|
6
|
+
export interface Place {
|
|
7
|
+
file: string
|
|
8
|
+
line: number
|
|
9
|
+
endLine?: number
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function place(doc: IRDocument, pos: SourcePos): Place {
|
|
13
|
+
return { file: relative(dirname(doc.meta.entry), pos.file) || pos.file, line: pos.line, ...pos.endLine ? { endLine: pos.endLine } : {} }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function findSection(doc: IRDocument, ref: string | number): IRSection {
|
|
17
|
+
const section = doc.sections.find(s => s.id === String(ref)) ?? doc.sections.find(s => String(s.index) === String(ref))
|
|
18
|
+
if (!section) throw new Error(`no section ${JSON.stringify(ref)}; list_sections names them`)
|
|
19
|
+
return section
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function findBlock(section: IRSection, id: string): IRBlock {
|
|
23
|
+
const block = [...irBlocks(section.blocks)].find(b => b.id === id)
|
|
24
|
+
if (!block) throw new Error(`no block ${JSON.stringify(id)} in section ${section.id}; get_section lists them`)
|
|
25
|
+
return block
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function sectionSummary(doc: IRDocument, section: IRSection) {
|
|
29
|
+
return {
|
|
30
|
+
id: section.id,
|
|
31
|
+
index: section.index,
|
|
32
|
+
title: section.title,
|
|
33
|
+
depth: section.depth,
|
|
34
|
+
steps: section.steps,
|
|
35
|
+
source: place(doc, section.source),
|
|
36
|
+
...section.audience ? { audience: section.audience } : {},
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function deckInfo(doc: IRDocument, document: string) {
|
|
41
|
+
const count = (severity: Finding['severity']) => doc.diagnostics.filter(f => f.severity === severity).length
|
|
42
|
+
return {
|
|
43
|
+
document,
|
|
44
|
+
title: doc.meta.title,
|
|
45
|
+
lang: doc.meta.lang,
|
|
46
|
+
entry: place(doc, { file: doc.meta.entry, line: 1 }).file,
|
|
47
|
+
sections: doc.sections.length,
|
|
48
|
+
steps: doc.sections.reduce((sum, s) => sum + s.steps + 1, 0),
|
|
49
|
+
plugins: doc.config.plugins,
|
|
50
|
+
renderers: Object.keys(doc.config.renderers),
|
|
51
|
+
diagnostics: { errors: count('error'), warnings: count('warning'), infos: count('info') },
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function origin(node: CodeNode) {
|
|
56
|
+
if (!node.origin) return undefined
|
|
57
|
+
const { anchor, file, startLine, endLine, status, drift, pin, permalink } = node.origin
|
|
58
|
+
return { anchor, file, startLine, endLine, status, ...drift ? { drift } : {}, ...pin ? { pin } : {}, ...permalink ? { permalink } : {} }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function blockInfo(doc: IRDocument, block: IRBlock, step?: number) {
|
|
62
|
+
const { node } = block
|
|
63
|
+
const state = step === undefined ? undefined : blockState(block, step)
|
|
64
|
+
const base = {
|
|
65
|
+
id: block.id,
|
|
66
|
+
role: block.role,
|
|
67
|
+
kind: node.type === 'component' ? node.name : node.type,
|
|
68
|
+
at: block.at,
|
|
69
|
+
...block.until !== undefined ? { until: block.until } : {},
|
|
70
|
+
...block.span ? { span: block.span } : {},
|
|
71
|
+
...block.only ? { only: block.only } : {},
|
|
72
|
+
...block.audience ? { audience: block.audience } : {},
|
|
73
|
+
source: place(doc, block.source),
|
|
74
|
+
}
|
|
75
|
+
if (node.type !== 'code') return { ...base, text: blockText(block) }
|
|
76
|
+
const variant = state !== undefined ? node.variants?.[state] : undefined
|
|
77
|
+
return {
|
|
78
|
+
...base,
|
|
79
|
+
lang: node.lang,
|
|
80
|
+
...node.title ? { title: node.title } : {},
|
|
81
|
+
code: variant?.value ?? node.value,
|
|
82
|
+
...variant ? { variant: variant.label } : {},
|
|
83
|
+
...state !== undefined && node.highlight?.[state] ? { highlight: node.highlight[state] } : {},
|
|
84
|
+
...node.origin ? { origin: origin(node) } : {},
|
|
85
|
+
...node.run ? { run: node.run.when } : {},
|
|
86
|
+
...node.outputs?.length ? { recorded: true } : {},
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function narration(section: IRSection) {
|
|
91
|
+
return section.blocks.filter(b => b.role === 'narration').map(b => ({ step: b.at, block: b.id, text: blockText(b) }))
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function sectionDetail(doc: IRDocument, section: IRSection) {
|
|
95
|
+
return {
|
|
96
|
+
...sectionSummary(doc, section),
|
|
97
|
+
narration: narration(section),
|
|
98
|
+
blocks: section.blocks.filter(b => b.role === 'visual').map(b => blockInfo(doc, b)),
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function stepDetail(doc: IRDocument, section: IRSection, step: number) {
|
|
103
|
+
if (!Number.isInteger(step) || step < 0 || step > section.steps) throw new Error(`section ${section.id} has steps 0 to ${section.steps}`)
|
|
104
|
+
return {
|
|
105
|
+
section: section.id,
|
|
106
|
+
title: section.title,
|
|
107
|
+
step,
|
|
108
|
+
steps: section.steps,
|
|
109
|
+
screen: section.blocks.filter(b => b.role === 'visual' && blockVisible(b, step)).map(b => blockInfo(doc, b, step)),
|
|
110
|
+
narration: narrationAt(section, step).map(b => blockText(b)),
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function codeRef(doc: IRDocument, section: IRSection, id: string) {
|
|
115
|
+
const block = findBlock(section, id)
|
|
116
|
+
if (block.node.type !== 'code') throw new Error(`block ${id} of section ${section.id} is not code`)
|
|
117
|
+
const { node } = block
|
|
118
|
+
return {
|
|
119
|
+
section: section.id,
|
|
120
|
+
block: id,
|
|
121
|
+
lang: node.lang,
|
|
122
|
+
...node.title ? { title: node.title } : {},
|
|
123
|
+
code: node.value,
|
|
124
|
+
source: place(doc, block.source),
|
|
125
|
+
origin: origin(node) ?? null,
|
|
126
|
+
...node.variants ? { variants: node.variants.map(v => ({ label: v.label, ...v.startLine ? { startLine: v.startLine, endLine: v.endLine } : {} })) } : {},
|
|
127
|
+
...node.highlight ? { highlight: node.highlight } : {},
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const TEXT = /^(text\/|application\/(json|javascript)$)/
|
|
132
|
+
|
|
133
|
+
function outputData(output: RunOutput) {
|
|
134
|
+
if (output.output_type !== 'display_data' && output.output_type !== 'execute_result') return output
|
|
135
|
+
const data = Object.fromEntries(Object.entries(output.data).map(([mime, value]) =>
|
|
136
|
+
[mime, TEXT.test(mime) ? (typeof value === 'string' ? value : Array.isArray(value) ? value.join('') : JSON.stringify(value)) : `(${mime} data)`]))
|
|
137
|
+
return { output_type: output.output_type, data }
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function runInfo(run: RunResult | RecordedRun) {
|
|
141
|
+
return {
|
|
142
|
+
ok: run.ok,
|
|
143
|
+
exitCode: run.exitCode,
|
|
144
|
+
timedOut: run.timedOut,
|
|
145
|
+
executor: run.executorId,
|
|
146
|
+
stdout: run.stdout,
|
|
147
|
+
stderr: run.stderr,
|
|
148
|
+
...run.outputs?.length ? { outputs: run.outputs.map(outputData) } : {},
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function outputsOf(section: IRSection, id?: string) {
|
|
153
|
+
const blocks = id ? [findBlock(section, id)] : [...irBlocks(section.blocks)]
|
|
154
|
+
return {
|
|
155
|
+
section: section.id,
|
|
156
|
+
outputs: blocks.flatMap(block => block.node.type === 'code' && (id || block.node.outputs?.length)
|
|
157
|
+
? [{ block: block.id, lang: block.node.lang, runs: (block.node.outputs ?? []).map(runInfo) }]
|
|
158
|
+
: []),
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function diagnosticsOf(doc: IRDocument, findings: Finding[]) {
|
|
163
|
+
return findings.map(f => ({
|
|
164
|
+
severity: f.severity,
|
|
165
|
+
check: f.checkId,
|
|
166
|
+
message: f.message,
|
|
167
|
+
...f.source ? place(doc, { file: f.source.file, line: f.source.line ?? 1 }) : {},
|
|
168
|
+
...f.hint ? { hint: f.hint } : {},
|
|
169
|
+
}))
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function locate(doc: IRDocument, target: { section?: string, step?: number, block?: string, anchor?: string }) {
|
|
173
|
+
if (target.anchor) {
|
|
174
|
+
const found = doc.sections.flatMap(section => [...irBlocks(section.blocks)]
|
|
175
|
+
.filter(b => b.node.type === 'code' && b.node.origin?.anchor === target.anchor)
|
|
176
|
+
.map(b => ({ section: section.id, block: b.id, source: place(doc, b.source), code: origin(b.node as CodeNode) })))
|
|
177
|
+
if (found.length === 0) throw new Error(`no code block references ${target.anchor}`)
|
|
178
|
+
return { anchor: target.anchor, references: found }
|
|
179
|
+
}
|
|
180
|
+
if (!target.section) throw new Error('name a section, or an anchor')
|
|
181
|
+
const section = findSection(doc, target.section)
|
|
182
|
+
if (target.block) return { section: section.id, block: target.block, source: place(doc, findBlock(section, target.block).source) }
|
|
183
|
+
if (target.step !== undefined) {
|
|
184
|
+
const blocks = section.blocks.filter(b => b.at === target.step)
|
|
185
|
+
return { section: section.id, step: target.step, blocks: blocks.map(b => ({ block: b.id, role: b.role, source: place(doc, b.source) })) }
|
|
186
|
+
}
|
|
187
|
+
return { section: section.id, source: place(doc, section.source) }
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const indexes = new WeakMap<IRDocument, MiniSearch>()
|
|
191
|
+
|
|
192
|
+
function searchIndex(doc: IRDocument): MiniSearch {
|
|
193
|
+
let index = indexes.get(doc)
|
|
194
|
+
if (index) return index
|
|
195
|
+
index = new MiniSearch({ fields: ['title', 'titles', 'text'], storeFields: ['title', 'titles'], tokenize })
|
|
196
|
+
index.addAll(chapters(doc).flatMap(chapter => chapter.sections.map((section, i) => ({
|
|
197
|
+
id: section.id,
|
|
198
|
+
title: section.title,
|
|
199
|
+
titles: i === 0 ? [] : [chapter.title],
|
|
200
|
+
text: section.blocks.map(blockText).filter(Boolean).join('\n'),
|
|
201
|
+
}))))
|
|
202
|
+
indexes.set(doc, index)
|
|
203
|
+
return index
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function search(doc: IRDocument, query: string, limit = 10) {
|
|
207
|
+
const results = searchIndex(doc).search(query, { fuzzy: 0.2, prefix: true, boost: { title: 4, text: 2, titles: 1 } })
|
|
208
|
+
return {
|
|
209
|
+
query,
|
|
210
|
+
results: results.slice(0, limit).map(r => ({ section: r.id as string, title: r.title as string, titles: r.titles as string[], score: Math.round(r.score * 100) / 100 })),
|
|
211
|
+
}
|
|
212
|
+
}
|
package/src/focus.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs'
|
|
2
|
+
import { dirname, isAbsolute, join, normalize, sep } from 'node:path'
|
|
3
|
+
import { docBlocks, isRecord } from '@lincyaw/kernel'
|
|
4
|
+
import type { Focus, FocusReport, IRDocument, SourceRange } from '@lincyaw/kernel'
|
|
5
|
+
import { findBlock, findSection, place } from './deck.ts'
|
|
6
|
+
|
|
7
|
+
export const EXCERPT_LINES = 20
|
|
8
|
+
const QUOTE_CHARS = 2000
|
|
9
|
+
const FROM = new Set<Focus['from']>(['source', 'web', 'slides'])
|
|
10
|
+
|
|
11
|
+
const str = (value: unknown, max = 200) => (typeof value === 'string' && value !== '' && value.length <= max ? value : undefined)
|
|
12
|
+
const line = (value: unknown) => (typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : undefined)
|
|
13
|
+
|
|
14
|
+
export function focusReport(value: unknown): FocusReport | string {
|
|
15
|
+
if (!isRecord(value)) return 'a focus is an object'
|
|
16
|
+
const id = str(value.id)
|
|
17
|
+
const from = value.from as Focus['from']
|
|
18
|
+
if (!id) return 'a focus has an id'
|
|
19
|
+
if (!FROM.has(from)) return 'a focus is from source, web or slides'
|
|
20
|
+
const source = isRecord(value.source) ? value.source : undefined
|
|
21
|
+
const range = source && str(source.file, 1000) && line(source.startLine) ? { file: source.file as string, startLine: source.startLine as number, endLine: line(source.endLine) ?? source.startLine as number } : undefined
|
|
22
|
+
if (source && !range) return 'a focus\'s source is { file, startLine, endLine }'
|
|
23
|
+
const report: FocusReport = { id, from }
|
|
24
|
+
for (const key of ['section', 'block'] as const) if (str(value[key])) report[key] = value[key] as string
|
|
25
|
+
if (typeof value.step === 'number' && Number.isInteger(value.step) && value.step >= 0) report.step = value.step
|
|
26
|
+
if (typeof value.quote === 'string' && value.quote.trim()) report.quote = value.quote.slice(0, QUOTE_CHARS)
|
|
27
|
+
if (range) report.source = range
|
|
28
|
+
if (!report.section && !report.block && !report.source) return 'a focus names a section, a block or a range of the source'
|
|
29
|
+
return report
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function excerptOf(text: string, start: number, end: number): string {
|
|
33
|
+
const lines = text.split(/\r?\n/).slice(start - 1, end)
|
|
34
|
+
if (lines.length <= EXCERPT_LINES) return lines.join('\n')
|
|
35
|
+
const half = EXCERPT_LINES / 2
|
|
36
|
+
return [...lines.slice(0, half), `[… ${lines.length - EXCERPT_LINES} more lines …]`, ...lines.slice(-half)].join('\n')
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function blockAt(doc: IRDocument, range: SourceRange): { section: string, block?: string } | undefined {
|
|
40
|
+
let found: { section: string, block: string, span: number } | undefined
|
|
41
|
+
for (const { section, block } of docBlocks(doc)) {
|
|
42
|
+
const at = place(doc, block.source)
|
|
43
|
+
const end = at.endLine ?? at.line
|
|
44
|
+
if (at.file !== range.file || range.startLine < at.line || range.startLine > end) continue
|
|
45
|
+
if (!found || end - at.line < found.span) found = { section: section.id, block: block.id, span: end - at.line }
|
|
46
|
+
}
|
|
47
|
+
if (found) return { section: found.section, block: found.block }
|
|
48
|
+
const sections = doc.sections.filter((s) => {
|
|
49
|
+
const at = place(doc, s.source)
|
|
50
|
+
return at.file === range.file && at.line <= range.startLine
|
|
51
|
+
})
|
|
52
|
+
const section = sections.at(-1)
|
|
53
|
+
return section && { section: section.id }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function resolveFocus(doc: IRDocument, document: string, report: FocusReport, read: (file: string) => string = file => readFileSync(file, 'utf8')): Focus {
|
|
57
|
+
const deckDir = dirname(doc.meta.entry)
|
|
58
|
+
let source: SourceRange
|
|
59
|
+
let section = report.section
|
|
60
|
+
let block = report.block
|
|
61
|
+
if (report.block || (report.section && !report.source)) {
|
|
62
|
+
const found = findSection(doc, report.section ?? [...docBlocks(doc)].find(b => b.block.id === report.block)?.section.id ?? '')
|
|
63
|
+
section = found.id
|
|
64
|
+
const at = report.block ? place(doc, findBlock(found, report.block).source) : place(doc, found.source)
|
|
65
|
+
source = { file: at.file, startLine: at.line, endLine: at.endLine ?? at.line }
|
|
66
|
+
} else {
|
|
67
|
+
const range = report.source!
|
|
68
|
+
const file = normalize(range.file)
|
|
69
|
+
if (isAbsolute(file) || file === '..' || file.startsWith(`..${sep}`)) throw new Error(`the file ${range.file} is not in the document directory`)
|
|
70
|
+
source = { file, startLine: range.startLine, endLine: Math.max(range.startLine, range.endLine) }
|
|
71
|
+
const at = blockAt(doc, source)
|
|
72
|
+
section ??= at?.section
|
|
73
|
+
block ??= at?.block
|
|
74
|
+
}
|
|
75
|
+
const excerpt = excerptOf(read(join(deckDir, source.file)), source.startLine, source.endLine)
|
|
76
|
+
return {
|
|
77
|
+
id: report.id,
|
|
78
|
+
from: report.from,
|
|
79
|
+
document,
|
|
80
|
+
source,
|
|
81
|
+
excerpt,
|
|
82
|
+
...section ? { section } : {},
|
|
83
|
+
...block ? { block } : {},
|
|
84
|
+
...report.step !== undefined ? { step: report.step } : {},
|
|
85
|
+
...report.quote ? { quote: report.quote } : {},
|
|
86
|
+
}
|
|
87
|
+
}
|