@native-knowledge/cli 0.0.0-stage → 0.1.0-rc.2
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/NOTICE +29 -0
- package/README.md +34 -2
- package/dist/agent-entry-cli.js +88 -0
- package/dist/auth-commands.js +102 -0
- package/dist/cli.js +104 -0
- package/dist/commands.js +17 -0
- package/dist/download.js +45 -0
- package/dist/errors.js +7 -0
- package/dist/input.js +89 -0
- package/dist/internal/contracts/artifact.js +103 -0
- package/dist/internal/contracts/collection-control.js +69 -0
- package/dist/internal/contracts/collection.js +174 -0
- package/dist/internal/contracts/common.js +16 -0
- package/dist/internal/contracts/currentness.js +221 -0
- package/dist/internal/contracts/event.js +35 -0
- package/dist/internal/contracts/evidence.js +171 -0
- package/dist/internal/contracts/index.js +54 -0
- package/dist/internal/contracts/material-capability.js +8 -0
- package/dist/internal/contracts/material-carrier.js +15 -0
- package/dist/internal/contracts/material-context.js +9 -0
- package/dist/internal/contracts/material-read.js +12 -0
- package/dist/internal/contracts/observation.js +39 -0
- package/dist/internal/contracts/persistence.js +239 -0
- package/dist/internal/contracts/project-intent.js +121 -0
- package/dist/internal/contracts/projection.js +194 -0
- package/dist/internal/contracts/public-reference.js +87 -0
- package/dist/internal/contracts/reference-record.js +55 -0
- package/dist/internal/contracts/remote-file.js +159 -0
- package/dist/internal/contracts/resource-scope.js +38 -0
- package/dist/internal/contracts/review-packet.js +61 -0
- package/dist/internal/contracts/review-plane.js +89 -0
- package/dist/internal/contracts/rich-document.js +184 -0
- package/dist/internal/contracts/runtime-compatibility.js +55 -0
- package/dist/internal/contracts/runtime.js +68 -0
- package/dist/internal/contracts/scheduler.js +256 -0
- package/dist/internal/contracts/signal.js +77 -0
- package/dist/internal/contracts/source-governance.js +194 -0
- package/dist/internal/contracts/source.js +32 -0
- package/dist/internal/contracts/tenant-budget.js +34 -0
- package/dist/internal/contracts/tenant-collection-request.js +58 -0
- package/dist/internal/contracts/tenant-collection.js +66 -0
- package/dist/internal/contracts/tenant-currentness.js +26 -0
- package/dist/internal/contracts/tenant-management.js +27 -0
- package/dist/internal/contracts/tenant-material-api.js +46 -0
- package/dist/internal/contracts/tenant-material-json-schema.js +16 -0
- package/dist/internal/contracts/tenant-pdf-text.js +13 -0
- package/dist/internal/contracts/tenant-project-control.js +19 -0
- package/dist/internal/contracts/tenant-public-reference.js +26 -0
- package/dist/internal/contracts/tenant-resource-api.js +70 -0
- package/dist/internal/contracts/tenant-resource.js +118 -0
- package/dist/internal/contracts/tenant-rich-document.js +17 -0
- package/dist/internal/contracts/tenant-source-binding.js +33 -0
- package/dist/internal/contracts/tenant-source-bridge.js +9 -0
- package/dist/internal/contracts/tenant-source-cutover.js +26 -0
- package/dist/internal/contracts/tenant-source-document.js +38 -0
- package/dist/internal/contracts/tenant-source-lease.js +5 -0
- package/dist/internal/contracts/tenant-source.js +83 -0
- package/dist/internal/contracts/tenant-web-collection.js +118 -0
- package/dist/internal/contracts/tenant-web-content-plan.js +39 -0
- package/dist/internal/contracts/tenant-web-content-result.js +15 -0
- package/dist/internal/contracts/tenant-web-content.js +16 -0
- package/dist/internal/contracts/tenant-web-crawl.js +55 -0
- package/dist/internal/contracts/tenant-web-dynamic.js +68 -0
- package/dist/internal/contracts/tenant-web-results.js +41 -0
- package/dist/internal/contracts/tenant-web-workflow.js +29 -0
- package/dist/internal/serving-contracts/agent-catalog.js +56 -0
- package/dist/internal/serving-contracts/agent-entry.js +57 -0
- package/dist/internal/serving-contracts/agent-guidance-shapes.js +12 -0
- package/dist/internal/serving-contracts/agent-input-hints.js +104 -0
- package/dist/internal/serving-contracts/body-search.js +16 -0
- package/dist/internal/serving-contracts/consumer.js +45 -0
- package/dist/internal/serving-contracts/core.js +76 -0
- package/dist/internal/serving-contracts/http.js +64 -0
- package/dist/internal/serving-contracts/index.js +25 -0
- package/dist/internal/serving-contracts/management.js +15 -0
- package/dist/internal/serving-contracts/material-capabilities.js +14 -0
- package/dist/internal/serving-contracts/material-index-status.js +5 -0
- package/dist/internal/serving-contracts/mcp.js +140 -0
- package/dist/internal/serving-contracts/tenant-governance.js +13 -0
- package/dist/internal/serving-contracts/tenant-management.js +89 -0
- package/dist/internal/serving-contracts/tenant-project.js +39 -0
- package/dist/internal/serving-contracts/tenant-runtime.js +37 -0
- package/dist/internal/serving-contracts/tenant-session.js +8 -0
- package/dist/internal/serving-contracts/tenant-web-content.js +20 -0
- package/dist/internal/serving-contracts/tenant-web-crawl.js +13 -0
- package/dist/internal/serving-contracts/tenant-web-dynamic.js +20 -0
- package/dist/internal/serving-contracts/tenant-web-workflow.js +36 -0
- package/dist/internal/serving-contracts/tenant-web.js +53 -0
- package/dist/internal/serving-contracts/tenant-workspace.js +28 -0
- package/dist/internal/serving-contracts/workflow.js +37 -0
- package/dist/profile-store.js +142 -0
- package/package.json +26 -3
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/NOTICE
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
native-knowledge SDK and CLI
|
|
2
|
+
Copyright (c) 2026 native-knowledge contributors
|
|
3
|
+
|
|
4
|
+
This release is licensed under the Apache License, Version 2.0.
|
|
5
|
+
The existing public 0.1.0-rc.1 packages were distributed under MIT.
|
|
6
|
+
The following historical copyright and permission notice is retained for
|
|
7
|
+
portions carried forward from those packages:
|
|
8
|
+
|
|
9
|
+
MIT License
|
|
10
|
+
|
|
11
|
+
Copyright (c) 2026 native-knowledge contributors
|
|
12
|
+
|
|
13
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
14
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
15
|
+
in the Software without restriction, including without limitation the rights
|
|
16
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
17
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
18
|
+
furnished to do so, subject to the following conditions:
|
|
19
|
+
|
|
20
|
+
The above copyright notice and this permission notice shall be included in all
|
|
21
|
+
copies or substantial portions of the Software.
|
|
22
|
+
|
|
23
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
24
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
25
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
26
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
27
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
28
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
29
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,35 @@
|
|
|
1
|
-
#
|
|
1
|
+
# native-knowledge CLI
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Remote Tenant and Agent-native client. Requires Node.js 24 or newer.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pnpm add --global @native-knowledge/cli@next
|
|
7
|
+
native-knowledge help
|
|
8
|
+
native-knowledge discover --server https://knowledge.example.com
|
|
9
|
+
native-knowledge auth login --server https://knowledge.example.com
|
|
10
|
+
native-knowledge auth whoami
|
|
11
|
+
native-knowledge tool list
|
|
12
|
+
native-knowledge auth logout
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
`knowledge-v2` is a compatible alias for the same remote client. stdout is one
|
|
16
|
+
JSON result; `--human` formats that result. `help` describes supported commands,
|
|
17
|
+
inputs and connection options. Agent discovery, typed tool calls and resource
|
|
18
|
+
downloads use the same server authorization as the SDK.
|
|
19
|
+
|
|
20
|
+
The service must admit the native public client and requested scopes. Browser
|
|
21
|
+
consent and PKCE bind the actual loopback callback. Tenant management additionally
|
|
22
|
+
requires current membership, client/audience delegation and runtime bindings;
|
|
23
|
+
successful login alone does not grant management authority.
|
|
24
|
+
|
|
25
|
+
Login creates private local profile and credential files. Do not copy credentials
|
|
26
|
+
into scripts, source control or shared configuration. Noninteractive business
|
|
27
|
+
commands do not open a browser or silently log in. Unknown mutation outcomes
|
|
28
|
+
require a read-only status check; do not blindly replay them.
|
|
29
|
+
|
|
30
|
+
The CLI does not open a business database, read local CAS, run collectors, use
|
|
31
|
+
SSH or expose Host maintenance. Retired local database flags and commands fail
|
|
32
|
+
before local business access. Install does not start services or collection.
|
|
33
|
+
|
|
34
|
+
Pin an exact qualified version for repeatable installs. Prereleases use `next`.
|
|
35
|
+
License: Apache-2.0. Historical MIT notices are retained in NOTICE.
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/** Network agent entry uses the same authenticated v26 SDK as MCP; no local authority shortcut. */
|
|
2
|
+
import { smallFile as inputFile } from './input.js';
|
|
3
|
+
import { KnowledgeAgentClient, KnowledgeAgentGuidanceError, TenantManagementSdkError, AuthError, TenantOperationUnknownError } from '@native-knowledge/knowledge-sdk';
|
|
4
|
+
import { agentCatalog, agentCapabilityNameSchema, agentEntryToolSchemas, agentTaskInputSchema } from './internal/serving-contracts/index.js';
|
|
5
|
+
const localErrorCodes = new Set(['AGENT_CLI_INPUT_INVALID', 'AGENT_CLI_INPUT_BUDGET', 'AGENT_CLI_FLAG_UNKNOWN', 'AGENT_CLI_FLAG_REQUIRED_OR_DUPLICATE']);
|
|
6
|
+
class AgentCliError extends Error {
|
|
7
|
+
code;
|
|
8
|
+
constructor(code) {
|
|
9
|
+
super(code);
|
|
10
|
+
this.code = code;
|
|
11
|
+
this.name = 'AgentCliError';
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
export function agentEntryHelp() {
|
|
15
|
+
return [
|
|
16
|
+
'native-knowledge — Agent-native knowledge entry (alias: knowledge-v2)',
|
|
17
|
+
'Plan a complex task: agent task --goal "研究资料并整理报告" --server <url> --tenant-id <id>',
|
|
18
|
+
'Recall capabilities: agent find --query "搜索已保存的资料" --server <url> --tenant-id <id>',
|
|
19
|
+
'Browse categories: agent find --server <url> --tenant-id <id>',
|
|
20
|
+
'Inspect one schema: agent tool --tool <name> --server <url> --tenant-id <id>',
|
|
21
|
+
'Complete parameters: agent input --tool <name> --input-json <partial JSON> --server <url> --tenant-id <id>',
|
|
22
|
+
'Execute explicitly: agent call --tool <name> --input-json <JSON> --server <url> --tenant-id <id>',
|
|
23
|
+
'Discovery supports --category <id>, --limit <1..8>, --after <opaque>. Calls accept --input-file <JSON> and --guided for failure nextActions.',
|
|
24
|
+
'Token: KNOWLEDGE_V2_OAUTH_ACCESS_TOKEN or --token-file <file>. Local HTTP requires --allow-insecure-http.',
|
|
25
|
+
'Follow nextActions explicitly; retain exact refs, filters and continuation cursors.',
|
|
26
|
+
'All Tenant commands use remote APIs and the selected login profile.',
|
|
27
|
+
'Existing agent guide/plan/advance remain available.',
|
|
28
|
+
].join('\n');
|
|
29
|
+
}
|
|
30
|
+
async function smallFile(file, max) { return new TextDecoder('utf-8', { fatal: true }).decode(await inputFile(file, max)); }
|
|
31
|
+
export async function runAgentEntryCommand(command, flags, client) {
|
|
32
|
+
if (!['agent find', 'agent tool', 'agent call', 'agent task', 'agent input'].includes(command))
|
|
33
|
+
return { handled: false };
|
|
34
|
+
try {
|
|
35
|
+
const allowed = new Set(['server', 'tenant-id', 'token-file', 'allow-insecure-http', 'query', 'category', 'limit', 'after', 'tool', 'input-json', 'input-file', 'goal', 'guided', 'profile', 'config-dir', 'non-interactive', 'human', 'json']);
|
|
36
|
+
for (const key of flags.keys())
|
|
37
|
+
if (!allowed.has(key))
|
|
38
|
+
throw new Error('AGENT_CLI_FLAG_UNKNOWN:' + key);
|
|
39
|
+
const one = (key, required = false) => { const v = flags.get(key); if (v?.length !== 1) {
|
|
40
|
+
if (v || required)
|
|
41
|
+
throw new Error('AGENT_CLI_FLAG_REQUIRED_OR_DUPLICATE:' + key);
|
|
42
|
+
return undefined;
|
|
43
|
+
} return v[0]; };
|
|
44
|
+
if (flags.has('allow-insecure-http') && one('allow-insecure-http') !== 'true')
|
|
45
|
+
throw new Error('AGENT_CLI_INPUT_INVALID');
|
|
46
|
+
const tool = one('tool'), json = one('input-json'), file = one('input-file'), goal = one('goal'), guided = one('guided');
|
|
47
|
+
if (guided !== undefined && (guided !== 'true' || command !== 'agent call') || goal !== undefined && command !== 'agent task')
|
|
48
|
+
throw new Error('AGENT_CLI_INPUT_INVALID');
|
|
49
|
+
if (command === 'agent task' || command === 'agent input') {
|
|
50
|
+
if (json !== undefined && file !== undefined || ['query', 'category', 'limit', 'after'].some(k => flags.has(k)))
|
|
51
|
+
throw new Error('AGENT_CLI_INPUT_INVALID');
|
|
52
|
+
const input = JSON.parse(file !== undefined ? await smallFile(file, 131072) : json ?? '{}');
|
|
53
|
+
if (!input || typeof input !== 'object' || Array.isArray(input))
|
|
54
|
+
throw new Error('AGENT_CLI_INPUT_INVALID');
|
|
55
|
+
if (command === 'agent input')
|
|
56
|
+
return { handled: true, value: await client.inputGuide(agentCapabilityNameSchema.parse(tool), input) };
|
|
57
|
+
if (tool !== undefined || Object.hasOwn(input, 'goal'))
|
|
58
|
+
throw new Error('AGENT_CLI_INPUT_INVALID');
|
|
59
|
+
return { handled: true, value: await client.planTask(agentTaskInputSchema.parse({ ...input, goal: one('goal', true) })) };
|
|
60
|
+
}
|
|
61
|
+
if (command === 'agent call') {
|
|
62
|
+
if (json !== undefined && file !== undefined || ['query', 'category', 'limit', 'after'].some(k => flags.has(k)))
|
|
63
|
+
throw new Error('AGENT_CLI_INPUT_INVALID');
|
|
64
|
+
const name = agentCapabilityNameSchema.parse(tool), input = JSON.parse(file !== undefined ? await smallFile(file, 131072) : json ?? '{}');
|
|
65
|
+
try {
|
|
66
|
+
return { handled: true, value: guided ? await client.guidedExecute(name, input) : await client.execute(name, input) };
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
if (!agentCatalog[name].readOnly && error instanceof TenantManagementSdkError && /TRANSPORT_FAILURE|RESPONSE_INVALID|HTTP_FAILURE/.test(error.code))
|
|
70
|
+
throw new TenantOperationUnknownError(input && typeof input === 'object' && typeof input.requestId === 'string' ? input.requestId : undefined, { completedPhase: error.completedPhase, ref: error.ref });
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
if (json !== undefined || file !== undefined || command === 'agent find' && tool || command === 'agent tool' && ['query', 'category', 'limit', 'after'].some(k => flags.has(k)))
|
|
75
|
+
throw new Error('AGENT_CLI_INPUT_INVALID');
|
|
76
|
+
const raw = command === 'agent tool' ? { tool: agentCapabilityNameSchema.parse(tool) } : Object.fromEntries(['query', 'category', 'limit', 'after'].filter(k => flags.has(k)).map(k => [k, k === 'limit' ? Number(one(k)) : one(k)]));
|
|
77
|
+
return { handled: true, value: await client.discover(agentEntryToolSchemas.knowledge_discover.parse(raw)) };
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
if (error instanceof Error && error.message === 'CLI_INPUT_BUDGET')
|
|
81
|
+
throw new AgentCliError('AGENT_CLI_INPUT_BUDGET');
|
|
82
|
+
if (error instanceof TenantManagementSdkError || error instanceof AuthError || error instanceof TenantOperationUnknownError)
|
|
83
|
+
throw error;
|
|
84
|
+
const candidate = error instanceof Error ? error.message.split(':', 1)[0] : '', code = localErrorCodes.has(candidate) ? candidate : 'AGENT_CLI_INPUT_INVALID';
|
|
85
|
+
throw new AgentCliError(code);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
export function agentEntryFailure(error) { return error instanceof AgentCliError ? { errorCode: error.code } : error instanceof TenantManagementSdkError ? { errorCode: error.code, status: error.status, ...(error.completedPhase ? { completedPhase: error.completedPhase } : {}), ...(error.ref ? { ref: error.ref } : {}), ...(error instanceof KnowledgeAgentGuidanceError ? { guidance: error.guidance } : {}) } : null; }
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { createServer } from 'node:http';
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { KnowledgeAuthClient, AuthError } from '@native-knowledge/knowledge-sdk';
|
|
4
|
+
import { ProfileStore } from './profile-store.js';
|
|
5
|
+
export function profileProvider(store, name, profile) {
|
|
6
|
+
const auth = new KnowledgeAuthClient({ ...profile, expectedIssuer: profile.session.issuer, expectedResource: profile.session.resource });
|
|
7
|
+
let seenGeneration = 0;
|
|
8
|
+
return { async getToken(options = {}) {
|
|
9
|
+
return store.lock(async () => {
|
|
10
|
+
const s = await store.secret(name);
|
|
11
|
+
if (!s || s.state !== 'READY')
|
|
12
|
+
throw new AuthError('AUTH_REAUTH_REQUIRED');
|
|
13
|
+
if (Date.parse(s.expiresAt) > Date.now() + 60000 && (!options.forceRefresh || seenGeneration !== s.generation)) {
|
|
14
|
+
seenGeneration = s.generation;
|
|
15
|
+
return s.accessToken;
|
|
16
|
+
}
|
|
17
|
+
await store.putSecret(name, { ...s, state: 'REFRESH_PENDING' });
|
|
18
|
+
try {
|
|
19
|
+
const t = await auth.refresh(profile.session.clientId, s.refreshToken, s.scopes);
|
|
20
|
+
await auth.session(t.accessToken, expectedSession(profile.session));
|
|
21
|
+
await store.putSecret(name, { ...t, generation: s.generation + 1, state: 'READY' });
|
|
22
|
+
seenGeneration = s.generation + 1;
|
|
23
|
+
return t.accessToken;
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
await store.putSecret(name, { ...s, state: 'REAUTH_REQUIRED' });
|
|
27
|
+
throw new AuthError('AUTH_REAUTH_REQUIRED');
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
} };
|
|
31
|
+
}
|
|
32
|
+
export async function login(store, input) {
|
|
33
|
+
if (input.nonInteractive)
|
|
34
|
+
throw new AuthError('AUTH_INTERACTION_REQUIRED');
|
|
35
|
+
const auth = new KnowledgeAuthClient(input), server = createServer();
|
|
36
|
+
let resolve, reject;
|
|
37
|
+
const callback = new Promise((a, b) => { resolve = a; reject = b; });
|
|
38
|
+
void callback.catch(() => { });
|
|
39
|
+
await new Promise((done, fail) => { server.once('error', fail); server.listen(input.port, '127.0.0.1', () => { server.off('error', fail); done(); }); }).catch(() => { throw new AuthError('AUTH_CALLBACK_PORT_UNAVAILABLE'); });
|
|
40
|
+
const address = server.address();
|
|
41
|
+
if (!address || typeof address === 'string')
|
|
42
|
+
throw new AuthError('AUTH_CALLBACK_PORT_UNAVAILABLE');
|
|
43
|
+
const redirectUri = `http://127.0.0.1:${address.port}/oauth/callback`;
|
|
44
|
+
const timer = setTimeout(() => reject(new AuthError('AUTH_CALLBACK_TIMEOUT')), input.timeoutMs), abort = () => reject(new AuthError('AUTH_CANCELLED'));
|
|
45
|
+
process.once('SIGINT', abort);
|
|
46
|
+
process.once('SIGTERM', abort);
|
|
47
|
+
try {
|
|
48
|
+
const transaction = await auth.begin({ clientId: input.clientId, redirectUri, scopes: input.scopes, authorityVersion: input.authorityVersion });
|
|
49
|
+
server.on('request', (req, res) => { if (req.method !== 'GET' || req.headers.host !== new URL(redirectUri).host || (req.url?.length ?? 0) > 8192) {
|
|
50
|
+
res.writeHead(400);
|
|
51
|
+
res.end();
|
|
52
|
+
return;
|
|
53
|
+
} const u = new URL(req.url ?? '', redirectUri); if (u.pathname !== '/oauth/callback') {
|
|
54
|
+
res.writeHead(404);
|
|
55
|
+
res.end();
|
|
56
|
+
return;
|
|
57
|
+
} res.writeHead(200, { 'content-type': 'text/plain', 'cache-control': 'no-store', 'content-security-policy': "default-src 'none'" }); res.end('Authorization received. Return to native-knowledge.'); resolve(u); });
|
|
58
|
+
process.stderr.write(JSON.stringify({ event: 'AUTHORIZATION_REQUIRED', authorizationUrl: transaction.authorizationUrl, callbackPort: address.port, expiresAt: new Date(transaction.expiresAt).toISOString(), sshForward: `ssh -L ${address.port}:127.0.0.1:${address.port} <host>` }) + '\n');
|
|
59
|
+
if (!input.noBrowser) {
|
|
60
|
+
const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'explorer.exe' : 'xdg-open';
|
|
61
|
+
const child = spawn(command, [transaction.authorizationUrl], { stdio: 'ignore', detached: true });
|
|
62
|
+
child.on('error', () => process.stderr.write(JSON.stringify({ event: 'AUTH_BROWSER_OPEN_FAILED', nextAction: 'Open the authorization URL in your browser.' }) + '\n'));
|
|
63
|
+
child.unref();
|
|
64
|
+
}
|
|
65
|
+
const url = await callback;
|
|
66
|
+
server.close();
|
|
67
|
+
const tokens = await auth.exchange(transaction, url), session = await auth.session(tokens.accessToken, { clientId: input.clientId, authorityVersion: input.authorityVersion, ...(input.expectedTenantId ? { tenantId: input.expectedTenantId } : {}) });
|
|
68
|
+
try {
|
|
69
|
+
await store.save(input.name, { baseUrl: input.baseUrl, allowInsecureHttp: input.allowInsecureHttp, session }, tokens);
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
for (const token of [tokens.accessToken, tokens.refreshToken])
|
|
73
|
+
await auth.revoke(input.clientId, token).catch(() => { });
|
|
74
|
+
throw new AuthError('AUTH_TOKEN_RESULT_UNKNOWN');
|
|
75
|
+
}
|
|
76
|
+
return session;
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
clearTimeout(timer);
|
|
80
|
+
process.off('SIGINT', abort);
|
|
81
|
+
process.off('SIGTERM', abort);
|
|
82
|
+
server.closeAllConnections();
|
|
83
|
+
if (server.listening)
|
|
84
|
+
await new Promise(r => server.close(() => r()));
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
export async function logout(store, name, profile) { return store.lock(async () => { const secret = await store.secret(name), auth = new KnowledgeAuthClient({ ...profile, expectedIssuer: profile.session.issuer, expectedResource: profile.session.resource }); let remoteRevocation = 'NOT_ATTEMPTED'; try {
|
|
88
|
+
if (secret) {
|
|
89
|
+
remoteRevocation = 'CONFIRMED';
|
|
90
|
+
for (const token of [secret.accessToken, secret.refreshToken])
|
|
91
|
+
try {
|
|
92
|
+
await auth.revoke(profile.session.clientId, token);
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
remoteRevocation = 'UNKNOWN';
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
await store.clear(name);
|
|
101
|
+
} return { localCleared: true, remoteRevocation }; }); }
|
|
102
|
+
export function expectedSession(s) { return { issuer: s.issuer, resource: s.resource, clientId: s.clientId, userId: s.userId, tenantId: s.tenantId, authorityVersion: s.authorityVersion }; }
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { cliFailure } from './errors.js';
|
|
3
|
+
import { runAgentEntryCommand } from './agent-entry-cli.js';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { KnowledgeAuthClient, KnowledgeTenantClient, KnowledgeAgentClient, AuthError } from '@native-knowledge/knowledge-sdk';
|
|
7
|
+
import { ProfileStore } from './profile-store.js';
|
|
8
|
+
import { login, logout, profileProvider, expectedSession } from './auth-commands.js';
|
|
9
|
+
import { commands, retired, help } from './commands.js';
|
|
10
|
+
import { parse, one, integer, smallFile, argumentsFor } from './input.js';
|
|
11
|
+
import { download } from './download.js';
|
|
12
|
+
let context, human = false;
|
|
13
|
+
async function main() {
|
|
14
|
+
const { command, flags: f } = parse(process.argv.slice(2));
|
|
15
|
+
human = f.has('human');
|
|
16
|
+
if (!command || command === 'help' || f.has('help'))
|
|
17
|
+
return help;
|
|
18
|
+
if (retired.has(command))
|
|
19
|
+
throw new AuthError('CLI_LOCAL_ACCESS_REMOVED');
|
|
20
|
+
if (!Object.hasOwn(commands, command) && !['auth login', 'auth status', 'auth whoami', 'auth logout', 'profile list', 'profile use', 'profile remove', 'discover', 'tool list', 'tool describe', 'tool call', 'resource file', 'agent find', 'agent tool', 'agent call', 'agent task', 'agent input'].includes(command))
|
|
21
|
+
throw new AuthError('CLI_TOOL_UNSUPPORTED');
|
|
22
|
+
const store = new ProfileStore(path.resolve(one(f, 'config-dir') ?? path.join(process.env.XDG_CONFIG_HOME ?? path.join(homedir(), '.config'), 'native-knowledge'))), profileName = one(f, 'profile');
|
|
23
|
+
if (command === 'profile list') {
|
|
24
|
+
const c = await store.config();
|
|
25
|
+
return { selected: c.selected, profiles: Object.entries(c.profiles).map(([name, p]) => ({ name, baseUrl: p.baseUrl, identity: p.session, verification: 'CACHED' })) };
|
|
26
|
+
}
|
|
27
|
+
if (command === 'profile use')
|
|
28
|
+
return store.use(profileName ?? one(f, 'name', true));
|
|
29
|
+
if (command === 'profile remove')
|
|
30
|
+
return store.remove(profileName ?? one(f, 'name', true));
|
|
31
|
+
if (command === 'auth login') {
|
|
32
|
+
context = await login(store, { name: profileName ?? 'default', baseUrl: one(f, 'server', true), clientId: one(f, 'client-id') ?? 'native-knowledge-cli', scopes: f.get('scope') ?? ['knowledge.material.read'], authorityVersion: integer(f, 'authority-version', 1, 1, 2), noBrowser: f.has('no-browser'), nonInteractive: f.has('non-interactive'), allowInsecureHttp: f.has('allow-insecure-http'), port: integer(f, 'callback-port', 0, 0, 65535), timeoutMs: integer(f, 'timeout-seconds', 300, 1, 300) * 1000, ...(one(f, 'tenant-id') ? { expectedTenantId: one(f, 'tenant-id') } : {}) });
|
|
33
|
+
return { authenticated: true };
|
|
34
|
+
}
|
|
35
|
+
if (command === 'auth status') {
|
|
36
|
+
try {
|
|
37
|
+
const { name, profile } = await store.selected(profileName), s = await store.secret(name);
|
|
38
|
+
return { profile: name, identity: profile.session, verification: 'CACHED', state: !s ? 'UNKNOWN' : s.state !== 'READY' ? 'REAUTH_REQUIRED' : Date.parse(s.expiresAt) <= Date.now() ? 'EXPIRED' : 'CACHED' };
|
|
39
|
+
}
|
|
40
|
+
catch (e) {
|
|
41
|
+
if (e instanceof AuthError && e.code === 'AUTH_REQUIRED')
|
|
42
|
+
return { state: 'UNKNOWN', verification: 'LOCAL' };
|
|
43
|
+
throw e;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (command === 'auth logout') {
|
|
47
|
+
const { name, profile } = await store.selected(profileName);
|
|
48
|
+
return logout(store, name, profile);
|
|
49
|
+
}
|
|
50
|
+
let selected;
|
|
51
|
+
try {
|
|
52
|
+
selected = await store.selected(profileName);
|
|
53
|
+
}
|
|
54
|
+
catch (e) {
|
|
55
|
+
if (!(e instanceof AuthError) || e.code !== 'AUTH_REQUIRED')
|
|
56
|
+
throw e;
|
|
57
|
+
}
|
|
58
|
+
const baseUrl = one(f, 'server') ?? selected?.profile.baseUrl;
|
|
59
|
+
if (!baseUrl)
|
|
60
|
+
throw new AuthError('AUTH_REQUIRED');
|
|
61
|
+
if (selected && one(f, 'server') && baseUrl !== selected.profile.baseUrl)
|
|
62
|
+
throw new AuthError('AUTH_CONTEXT_MISMATCH');
|
|
63
|
+
const allowInsecureHttp = f.has('allow-insecure-http') || selected?.profile.allowInsecureHttp === true, auth = new KnowledgeAuthClient({ baseUrl, allowInsecureHttp, ...(selected ? { expectedIssuer: selected.profile.session.issuer, expectedResource: selected.profile.session.resource } : {}) });
|
|
64
|
+
if (command === 'discover')
|
|
65
|
+
return auth.discover();
|
|
66
|
+
const tokenFile = one(f, 'token-file'), env = process.env.KNOWLEDGE_V2_OAUTH_ACCESS_TOKEN;
|
|
67
|
+
if ([Boolean(tokenFile), Boolean(env), Boolean(selected)].filter(Boolean).length !== 1)
|
|
68
|
+
throw new AuthError('AUTH_CREDENTIAL_SOURCE_CONFLICT');
|
|
69
|
+
const token = tokenFile ? (await smallFile(tokenFile, 4096)).toString('utf8').trim() : env, provider = selected ? profileProvider(store, selected.name, selected.profile) : undefined;
|
|
70
|
+
const credentials = provider ? { tokenProvider: provider } : { token: token };
|
|
71
|
+
const expected = selected ? expectedSession(selected.profile.session) : one(f, 'tenant-id') ? { tenantId: one(f, 'tenant-id') } : undefined;
|
|
72
|
+
try {
|
|
73
|
+
context = await auth.session(provider ? await provider.getToken() : token, expected);
|
|
74
|
+
}
|
|
75
|
+
catch (error) {
|
|
76
|
+
if (!(error instanceof AuthError) || error.status !== 401 || !provider)
|
|
77
|
+
throw error;
|
|
78
|
+
context = await auth.session(await provider.getToken({ forceRefresh: true }), expected);
|
|
79
|
+
}
|
|
80
|
+
if (one(f, 'tenant-id') && context.tenantId !== one(f, 'tenant-id'))
|
|
81
|
+
throw new AuthError('AUTH_CONTEXT_MISMATCH');
|
|
82
|
+
if (command === 'auth whoami')
|
|
83
|
+
return { verification: 'AUTHENTICATED_NOW', identity: context };
|
|
84
|
+
const entry = await runAgentEntryCommand(command, f, new KnowledgeAgentClient({ baseUrl, ...credentials, expectedTenantId: context.tenantId, allowInsecureHttp }));
|
|
85
|
+
if (entry.handled)
|
|
86
|
+
return entry.value;
|
|
87
|
+
const catalog = await auth.discover();
|
|
88
|
+
if (command === 'tool list')
|
|
89
|
+
return { tools: catalog.tools.map(t => ({ ...t, scopeSatisfied: t.scopeAlternatives.some(a => a.every(s => context.effectiveScopes.includes(s))) })) };
|
|
90
|
+
if (command === 'tool describe') {
|
|
91
|
+
const tool = catalog.tools.find(t => t.name === (one(f, 'tool') ?? one(f, 'name')));
|
|
92
|
+
if (!tool)
|
|
93
|
+
throw new AuthError('CLI_TOOL_UNSUPPORTED');
|
|
94
|
+
return tool;
|
|
95
|
+
}
|
|
96
|
+
const client = new KnowledgeTenantClient({ baseUrl, ...credentials, expectedTenantId: context.tenantId, allowInsecureHttp }), input = await argumentsFor(f, command);
|
|
97
|
+
if (command === 'resource file')
|
|
98
|
+
return download(client, f, input);
|
|
99
|
+
const name = command === 'agent status' && input.requestId ? 'tenant_operation_status' : command === 'tool call' ? one(f, 'tool', true) : commands[command];
|
|
100
|
+
if (!name || !catalog.tools.some(t => t.name === name))
|
|
101
|
+
throw new AuthError('CLI_TOOL_UNSUPPORTED');
|
|
102
|
+
return client.call(name, input);
|
|
103
|
+
}
|
|
104
|
+
main().then(data => process.stdout.write(JSON.stringify({ schemaVersion: 1, ok: true, ...(context ? { context } : {}), data }, null, human ? 2 : undefined) + '\n')).catch(e => { const f = cliFailure(e); process.stdout.write(JSON.stringify({ schemaVersion: 1, ok: false, ...(context ? { context } : {}), error: f.error }) + '\n'); process.exitCode = f.exit; });
|
package/dist/commands.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** 固定别名映射到原生工具;不存在可回退本地执行的分支。 */
|
|
2
|
+
export const commands = {
|
|
3
|
+
'agent guide': 'tenant_workflow_guide', 'agent plan': 'tenant_workflow_plan', 'agent advance': 'tenant_workflow_advance', 'agent submit': 'tenant_material_submit', 'agent status': 'tenant_workflow_plan',
|
|
4
|
+
'source list': 'tenant_source_list', 'source get': 'tenant_source_get', 'source define': 'tenant_source_define', 'source configure': 'tenant_source_configure',
|
|
5
|
+
'collection request': 'tenant_collection_request', 'collection status': 'tenant_collection_status',
|
|
6
|
+
'project list': 'tenant_project_list', 'project get': 'tenant_project_get', 'project materials': 'tenant_project_materials', 'project scope-set': 'tenant_project_scope_set', 'project lifecycle-set': 'tenant_project_lifecycle_set',
|
|
7
|
+
'runtime status': 'tenant_runtime_status', 'work queue': 'tenant_work_queue',
|
|
8
|
+
'artifact draft': 'tenant_artifact_draft', 'artifact review': 'tenant_knowledge_review', 'artifact promote': 'tenant_artifact_promote', 'knowledge compose': 'tenant_knowledge_compose', 'insight compose': 'tenant_knowledge_compose', 'knowledge read': 'tenant_knowledge_read',
|
|
9
|
+
'material share': 'tenant_material_share', 'material revoke': 'tenant_material_revoke', 'material routes': 'tenant_material_routes', 'snapshot declare': 'tenant_snapshot_declare', 'snapshot status': 'tenant_snapshot_status',
|
|
10
|
+
};
|
|
11
|
+
for (const op of ['list', 'describe', 'read', 'search', 'counts', 'window', 'changes', 'capabilities', 'media', 'index-status'])
|
|
12
|
+
commands['resource ' + op] = 'knowledge_resource_' + op.replaceAll('-', '_');
|
|
13
|
+
for (const op of ['preview', 'submit', 'status', 'results', 'cycles', 'read', 'pause', 'resume', 'cancel', 'refresh', 'index-status'])
|
|
14
|
+
commands['web-collect ' + op] = 'tenant_web_collect_' + (['pause', 'resume', 'cancel'].includes(op) ? 'control' : op.replaceAll('-', '_'));
|
|
15
|
+
export const localFlags = new Set(['data-root', 'identity-database', 'node-id', 'tenant', 'user', 'agent', 'cursor-secret-env', 'file-roots', 'browser-fallback', 'projection-mode', 'consumer-profile-file']);
|
|
16
|
+
export const retired = new Set(['project-intent put', 'project-intent get', 'source put', 'source preview', 'source add-url', 'source add-file', 'source add-executor', 'source reproject', 'source drift', 'source rebind', 'source due', 'batch create', 'batch create-due', 'batch get', 'batch collector-view', 'batch run', 'batch run-get', 'material page', 'material describe', 'material scope get', 'material scope set', 'material status', 'material publish', 'material location select', 'material put', 'artifact create', 'artifact get', 'artifact list', 'artifact index', 'artifact support', 'reference gap-audit', 'delivery content-factory project', 'delivery content-factory stage', 'delivery content-factory outbox-list', 'delivery content-factory record']);
|
|
17
|
+
export const help = { name: 'native-knowledge', alias: 'knowledge-v2', schemaVersion: 1, transport: 'REMOTE_OAUTH_TENANT', commands: ['auth login|status|whoami|logout', 'profile list|use|remove', 'discover', 'tool list|describe|call', 'resource file', 'agent find', 'agent tool', 'agent call', 'agent task', 'agent input', ...Object.keys(commands)], input: '--input-file <JSON> | --input-json <JSON>; --content-file <file> for submit/draft', connection: '--server <API-root> --profile <name> --token-file <file> --tenant-id <expected-Tenant>', login: 'auth login --server <API-root> --client-id <registered-native-client> [--scope <scope> ...] [--authority-version 1|2] [--no-browser] [--callback-port <port>]', rules: ['Tenant identity comes from the server session. Project is an explicit narrowing.', 'No database, local collection or Host maintenance access.', 'Noninteractive business calls never open a browser. stdout is one JSON result.'] };
|
package/dist/download.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { open, unlink } from 'node:fs/promises';
|
|
2
|
+
import { createWriteStream } from 'node:fs';
|
|
3
|
+
import { Readable, Transform } from 'node:stream';
|
|
4
|
+
import { pipeline } from 'node:stream/promises';
|
|
5
|
+
import { createHash } from 'node:crypto';
|
|
6
|
+
import { AuthError } from '@native-knowledge/knowledge-sdk';
|
|
7
|
+
import { one } from './input.js';
|
|
8
|
+
export async function download(client, f, input) {
|
|
9
|
+
if (typeof input.ref !== 'string')
|
|
10
|
+
throw new AuthError('CLI_INPUT_REQUIRED');
|
|
11
|
+
const output = one(f, 'output-file') ?? one(f, 'output');
|
|
12
|
+
if (!f.has('head') && !output)
|
|
13
|
+
throw new AuthError('CLI_INPUT_REQUIRED');
|
|
14
|
+
const response = await client.resources.stream(input.ref, { ...(f.has('head') ? { head: true } : {}), ...(one(f, 'range') ? { range: one(f, 'range') } : {}), ...(one(f, 'expected-content-hash') ? { expectedContentHash: one(f, 'expected-content-hash') } : {}), ...(typeof input.projectRef === 'string' ? { projectRef: input.projectRef } : {}) });
|
|
15
|
+
const { body, ...metadata } = response;
|
|
16
|
+
if (f.has('head'))
|
|
17
|
+
return metadata;
|
|
18
|
+
if (!body)
|
|
19
|
+
throw new AuthError('CLI_TRANSFER_FAILED');
|
|
20
|
+
let handle;
|
|
21
|
+
try {
|
|
22
|
+
handle = await open(output, 'wx', 0o600);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
await body.cancel();
|
|
26
|
+
throw new AuthError('CLI_OUTPUT_EXISTS_OR_UNAVAILABLE');
|
|
27
|
+
}
|
|
28
|
+
const hash = createHash('sha256');
|
|
29
|
+
let bytes = 0;
|
|
30
|
+
try {
|
|
31
|
+
await pipeline(Readable.fromWeb(body), new Transform({ transform(chunk, _encoding, done) { bytes += chunk.length; if (bytes > response.contentLength)
|
|
32
|
+
return done(new AuthError('CLI_TRANSFER_FAILED')); hash.update(chunk); done(null, chunk); } }), createWriteStream(output, { fd: handle.fd, autoClose: false }));
|
|
33
|
+
if (bytes !== response.contentLength || response.status !== 206 && 'sha256:' + hash.digest('hex') !== response.contentHash)
|
|
34
|
+
throw new AuthError('CLI_TRANSFER_INTEGRITY');
|
|
35
|
+
await handle.sync();
|
|
36
|
+
return { ...metadata, bytes, verification: response.status === 206 ? 'RANGE_BYTES_RECEIVED' : 'CLIENT_FULL_HASH_VERIFIED' };
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
await unlink(output).catch(() => { });
|
|
40
|
+
throw new AuthError('CLI_TRANSFER_FAILED');
|
|
41
|
+
}
|
|
42
|
+
finally {
|
|
43
|
+
await handle.close();
|
|
44
|
+
}
|
|
45
|
+
}
|